【问题标题】:map through object of objects to return object通过对象的对象映射到返回对象
【发布时间】:2023-02-09 15:43:26
【问题描述】:

我试着研究其他例子,但我不明白。 我正在尝试遍历对象的 obj 并返回具有键值对的对象。

const res =  {0 : {id: "id1", name: "name1" , rollno: "1"}, 1 : {id: "id2", name: "name2", rollno: "2"}}

const section = {"id1" : "section A", "id3" : "section B"}

const result = Object.entries(res).map((item) => ({id: item.id, name: item.name, section: section.[item.id]})).  // failing

//expected result = {0 : {id: "id1", name: "name1" , section: "section A"}, 1 : {id: "id2", name: "name2", section: "undefined"}}

【问题讨论】:

  • 只需将 Object.entries() 替换为 Object.values()。此外,它应该是section: section[item.id][] 之前没有.
  • 为什么 res 是一个带有数字索引的对象?为什么不是数组?

标签: javascript reactjs object


【解决方案1】:

这是因为对象条目返回一个数组,其中包含您传递的对象的键和值。

所以不是:

Object.entries(res).map((item)

你需要做:

Object.entries(res).map(([key, item])

【讨论】:

  • 啊!是的!我的错!谢谢
【解决方案2】:

嘿,您只需要向对象添加动态键值。

const res = {
  0: { id: "id1", name: "name1", rollno: "1" },
  1: { id: "id2", name: "name2", rollno: "2" },
};

const section = { id1: "section A", id2: "section B" };

let result = Object.entries(res).map((item, index) => {
  return  { [index]: {
    id: item[1].id,
    name: item[1].name,
    section: section[item[1].id],
  }} 
});
console.log(result);

【讨论】:

    猜你喜欢
    • 2018-05-30
    • 1970-01-01
    • 2019-09-19
    • 1970-01-01
    • 2017-01-01
    • 2021-02-17
    • 1970-01-01
    • 2021-09-22
    • 1970-01-01
    相关资源
    最近更新 更多