首页 > 解决方案 > 如何显示列表对象的信息

问题描述

我有按类别属性分类的书籍,如何获取书籍的描述值以显示在屏幕上?

已经尝试过使用values()和keys()

{1: Array(2), 2: Array(1), 4: Array(1), 9: Array(1)}

1: Array(2)
0: {id: 1, description: "teste", category: 1}
1: {id: 73, description: "basica tb", category: 1}
length: 2
__proto__: Array(0)
2: Array(1)
0: {id: 3, description: "Teoria das ideias", category: 2}
length: 1
__proto__: Array(0)
4: Array(1)
0: {id: 5, description: "Mr with research computer.", category: 4}
length: 1
__proto__: Array(0)
9: Array(1)
0: {id: 10, description: "Vote drug thus no.", category: 9}
length: 1
__proto__: Array(0)
__proto__: Object

我需要返回对象书目的标题

标签: javascriptarraysreactjsobject

解决方案


这段代码应该可以工作。使用Object.keysand reduce,map覆盖每个值并返回描述:

const data = {
    1: [
        {id: 1, description: "teste", category: 1},
        {id: 73, description: "basica tb", category: 1}
    ],
    2: [
        {id: 3, description: "Teoria das ideias", category: 2}
    ],
    4: [
        {id: 5, description: "Mr with research computer.", category: 4}
    ],
    9: [
        {id: 10, description: "Vote drug thus no.", category: 9}
    ]
}

const getDescription = data => Object.keys(data).reduce((a, key) => ({...a, [key]: data[key].map(o => o.description)}), {})

console.log(getDescription(data))


推荐阅读