我正在尝试缺乏更好的条款' zip'或者'合并' json对象基于每个中的单个重复出现的元素。例如:
var obj = {
CATS:[
{
id:123,
LIST:[
{result1:CAT1},
{result2:CAT2}
]
},
{
id:987,
LIST:[
{result1:CAT3},
{result2:CAT4}
]
}
],
DOGS:[
{
id:123,
LIST:[
{result1:DOG1},
{result2:DOG2}
]
},
{
id:987,
LIST:[
{result1:DOG3},
{result2:DOG4}
]
}
]
}
我想使用' id'嵌套在obj中以创建:
var new_obj = {
123:[
CATS:{
LIST:[
{result1:CAT1},
{result2:CAT2}
]
},
DOGS:{
LIST:[
{result1:DOG1},
{result2:DOG2}
]
}
],
987:[
CATS:{
LIST:[
{result1:CAT3},
{result2:CAT4}
]
},
DOGS:{
LIST:[
{result1:DOG3},
{result2:DOG4}
]
}
]
}
不偏爱LoDash或Underscore ......很高兴使用任何有用的东西。 谢谢!
**警告!必须是ie8兼容。的Bleh! **
答案 0 :(得分:2)
假设您希望输出中的123
键的值是哈希而不是数组,那么没有下划线或lodash:
Object.keys(obj).reduce( // Reduce the keys in the input
function(result, animals) { // by taking each key like DOGS
animals.forEach( // and for each of its
function(animal) { // elements (animal)
result[animal.id] = result[animal.id] || {}; // create an ID field in result
result[animal.id][animals] = animal.list; // add animal's list of results
});
return result; // and pass result to next key
},
{}
);
对于IE8,请使用相关的polyfill。或者使用下划线/ lodash等效进行明显的重写。
答案 1 :(得分:1)
经过一些反复试验,我可能会得到你所需要的......
var result = _.reduce(obj, function(memo, group, key) {
var ids = _.map(group, function(g) {
return g.id;
});
_.each(ids, function(id) {
var obj = {};
obj[key] = {};
obj[key].LIST = _.filter(group, function(g) {
return g.id === id;
}).map(function(g) {
return g.LIST;
})[0];
memo[id] = (memo[id] || []);
memo[id].push(obj);
});
return memo;
}, {});
检查一下...... http://jsbin.com/gabako/1/edit