javascript - 从 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: {}
}
关于如何达到预期结果的任何想法?
解决方案
您可以使用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)
推荐阅读
- docker - 如何批量删除特定正在运行的 docker 容器
- stm32 - STM32的外设寄存器在哪里?它们是在皮质-m 核心还是在外围单元本身?
- python - 两个像素访问对象之间返回错误的差异
- python - 如何为自己的 python 包的 init 集成设置文件的最佳实践?
- php - PHP - 基于日期时间间隔的数组值的平均值
- c# - 有没有办法可以编译一个 Mono 项目以在 linux 上本地运行?
- reactjs - React 应用程序中的 Firebase 实时数据库:如何访问这些值?
- javascript - 根据另一个对象对对象进行排序
- angular - 动态加载捆绑包时 SystemJS 未在 Safari 中发送 cookie
- swift - 删除 podfile.lock 并运行 pod install 后 Xcode 出错