首页 > 解决方案 > 从 ObjectsLoop 数组创建一个新对象

问题描述

我想遍历一个数组并创建/添加到另一个对象。

let list = [
    {id:1, parent_id: 1, location: "place1", content: "hello"}, 
    {id:2, parent_id: 2, location: "place2", content: "hello again"},
    {id:3, parent_id: 1, location: "place1", content: "hello"}
]

let newObjList = {
    place1: {},
    place2: {}
}

list.forEach(i => {
    let noteId = i.id
    let parentId = i.parent_id
    let location = i.location === "place1" 
                   ? "place1" :
                      i.location === "place2" 
                      ? "place2" : null;

    let existingKeyList = !!location ? Object.keys(newObjList[location]) : []

    let existingKeySet = new Set(existingKeyList)

    let listHasKey = existingKeySet.has(parentId)

    if(!listHasKey) {
        newObjList[itemType][parentId] = {}
        newObjList[itemType][parentId][noteId] = i
    } else {
        newObjList[itemType][parentId][noteId] = i
    }
})

最后,我希望新对象看起来像这样:

{
    place1: {
        1: {id:1, parent_id: 1, location: "place1", content: "hello"}, 
        3: {id:3, parent_id: 1, location: "place1", content: "hello"}
    },
    place2: {
        2: {id:2, parent_id: 2, location: "place2", content: "hello again"}
    }
}

我试图实现这forEach()一点只是从我的 newObjList 中的数组中返回最后一项。像这样:

newObjList: {
    place1: { 
        3: { id:3, parent_id: 1, location: "place1", content: "hello" }
    },
    place2: {}
}

关于如何达到预期结果的任何想法?

标签: javascriptecmascript-6

解决方案


您可以使用reduce-function 来实现这一点。

以下是一些资源: https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

https://www.w3schools.com/jsref/jsref_reduce.asp

以下是使用您的用例的示例。

let list = [{id:1, parent_id: 1, location: "place1", content: "hello"}, {id:2, parent_id: 2, location: "place2", content: "hello again"}, {id:3, parent_id: 1, location: "place1", content: "hello"}]
    
const myObject = list.reduce((prev, item) => {
  prev[item.location][item.id] = item;
  return prev;
}, {place1: {}, place2: {}});

console.log(myObject)


推荐阅读