【问题标题】:how can I show the information of a list object如何显示列表对象的信息
【发布时间】:2019-11-03 09:45:15
【问题描述】:

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

已经尝试过使用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

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

【问题讨论】:

  • 能否请您提供真实数据而不是从控制台复制。
  • 数据由api返回,我正在使用react并且我有一个接收这些数据的状态,我正在使用groupby函数按类别对它们进行分组,现在我需要显示例如: 类别 1 描述 1 描述 2 类别 2 描述 2 。 . . .
  • 为什么你的问题被 Python 标记了?
  • 对不起,我写错了。
  • @GustavoNogueira 你能举例说明你的预期输出吗?

标签: javascript arrays reactjs object


【解决方案1】:

这段代码应该可以工作。在每个值上使用Object.keysreducemap 并返回描述:

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))

【讨论】:

  • 抱歉,但当我尝试在屏幕上显示结果时出现此错误:对象作为 React 子项无效(找到:带键的对象 {})。如果您打算渲染一组子项,请改用数组。
【解决方案2】:

嗨,Gustavo,我不太确定您想要什么,但我认为您想要呈现您的对象列表。有很多方法可以做到这一点,但我将通过使用 javascript 高阶函数 map 向您展示最简单的方法。这个高阶函数让您可以循环遍历数组。

简单实例:

import React from 'react';

const List = () => {
      const data = [{
      name: 'Joe',
      age: '16'
      }]
      return (
      {data.map(data => <li key={data.age}>{data.name}</li>)}
)
}

【讨论】:

  • 你不能映射一个对象
  • 另外,data.Joe 将返回 undefined,您正在寻找 data.name
  • @GustavoNogueira 他们现在已经编辑了他们的代码?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多