gpt4 book ai didi

javascript - 如何在对象中设置对象?

转载 作者:行者123 更新时间:2023-11-30 17:24:14 25 4
gpt4 key购买 nike

我有两个对象映射;

var one = { '1': { id: 1, pid: 1, name: 'John'},
'3': { id: 35, pid: 3, name: 'Josh'},
'5': { id: 34, pid: 5, name: 'Joe'} }

var two = {1:1, 34:1, 35:1}

Object.keys(one).forEach(function(item){
two[one[item].id]= {pid : one[item]};
});

我想要的结果是

{1:  { '1': { id: 1, pid: 1, name: 'John'}, 34: {'3': { id: 34, pid: 3, name: 'Josh'}}, 35:{'5': { id: 35, pid: 5, name: 'Joe'}}}

但是我得到了

 {1:  { pid: { id: 1, pid: 1, name: 'John'}, 34: {pid: { id: 34, pid: 3, name: 'Josh'}}, pid:{'5': { id: 35, pid: 5, name: 'Joe'}}}

但我没有得到动态 pid,只有堆栈 pids。我知道上面的循环将它设置为静态 id,想解决它以获得动态 pid。

最佳答案

要获得良好的结果,只需像设置“id”一样将“pid”设置为键:

var one = { '1': { id: 1, pid: 1, name: 'John'},
'3': { id: 35, pid: 3, name: 'Josh'},
'5': { id: 34, pid: 5, name: 'Joe'} }

var two = {}

Object.keys(one).forEach(function(item){
var current = one[item]
// We initialize empty object
two[current.id]= {}
// We set the object at key .pid to what is wanted
two[current.id][current.pid] = current
})

console.log(two)

结果(JSON 格式):

{"1":{"1":{"id":1,"pid":1,"name":"John"}},"34":{"5":{"id":34,"pid":5,"name":"Joe"}},"35":{"3":{"id":35,"pid":3,"name":"Josh"}}} 

关于javascript - 如何在对象中设置对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24565734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com