我有两个对象图;
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,只有堆栈pid。我知道上面的循环将它设置为静态id,想要解决它以获得动态pid。
答案 0 :(得分:2)
为了获得好结果,只需设置" pid"就像你为" id":
所做的一样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"}}}
答案 1 :(得分:0)
你所说的你想要的并不是一个有效的对象。我猜你想要
var one = {
1: { id: 1, pid: 1, name: 'John'},
3: { id: 35, pid: 3, name: 'Josh'},
5: { id: 34, pid: 5, name: 'Joe'}
}, two = {};
Object.keys(one).forEach(function(item){
two[one[item].id]= one[item];
});
答案 2 :(得分:0)
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){
var obj = {};
obj[one[item].pid] = one[item];
two[one[item].id]= obj;
});
console.log (two);
答案 3 :(得分:0)
这应该适合你。
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};
for (key in one){
var item = one[key];
two[item.id] = {};
two[item.id][item.pid] = item;
}