Javascript IndexBy类型数组的嵌套对象值
我想执行以下转换,但在如何执行转换方面遇到了问题,只是想知道是否有人有任何指示:Javascript IndexBy类型数组的嵌套对象值,javascript,lodash,Javascript,Lodash,我想执行以下转换,但在如何执行转换方面遇到了问题,只是想知道是否有人有任何指示: //Source [ { types: ['a', 'b'] }, { types: ['b'] }, { types: ['a', 'c'] } ] //Transformation { 'a': [ { types: ['a', 'b'] }, { types: ['a', 'c'] } ], 'b': [ { types: ['a', 'b'] }, { types
//Source
[
{ types: ['a', 'b'] },
{ types: ['b'] },
{ types: ['a', 'c'] }
]
//Transformation
{
'a': [ { types: ['a', 'b'] }, { types: ['a', 'c'] } ],
'b': [ { types: ['a', 'b'] }, { types: ['b'] } ],
'c': [ { types: ['a', 'c'] } ]
}
将与
var数据=[{
类型:['a','b']
}, {
类型:['b']
}, {
类型:['a','c']
}];
var res=数据减少(函数(a,b){
b、 forEach(函数(v){//遍历内部数组
a[v]=a[v]| |[];//如果未定义,请定义属性
a[v].推(b);//推对象参照
});
返回a;
}, {});
document.write(''+JSON.stringify(res,0,3)+'')
我们可以使用数组的。reduce
进行迭代
var数据=[{
类型:['a','b']
}, {
类型:['b']
}, {
类型:['a','c']
}];
变量转换=函数(记录){
var obj={};
记录。forEach(函数(记录){
record.types.forEach(函数(值){
obj[value]=obj[value]| |[]
obj[值]。推送(记录);
});
});
返回obj;
};
document.write(“”+JSON.stringify(transform(data))+“”)代码>酷!!我们在同一页+1
var test = [
{ types: ['a', 'b'] },
{ types: ['b'] },
{ types: ['a', 'c'] }
]
test.reduce(function(res,obj,index){
obj.types.forEach(function(x){
res[x] = res[x] || [];
res[x].push(obj)
});
return res;
},{});