我有两个数组:
array1 = [{
"type":"test",
"name":"name1"},
{
"type":"dev",
"name":"name2"}]
array2=[{
"type":"test",
"name":"name3"},
{
"type":"dev",
"name":"name4"},
{
"type":"prod",
"name":"name5"}]
我想用“type”对两个数组进行分组,并创建一个像这样的新数组:
finalArray=[{
"type":"test",
"info":[{
"type":"test",
"name":"name1"}],
[{
"type":"test",
"name":"name3"
}]},
{
"type":"dev",
"info":[{
"type":"dev",
"name":"name2"}],
[{
"type":"dev",
"name":"name4"}]},
{
"type":"prod",
"info":[],
[{
"type":"prod",
"name":"name5"}]
}]
无论如何,我可以使用javascript,angularjs2,lodash,jquery来实现这一点。我可以按照using lodash .groupBy. how to add your own keys for grouped output?
中的提法对新对象进行分组和创建但唯一的事情总是我想把第二个数组中的数据推送到“info”的index = 1中,第一个数据推送到index = 0。如果任何数组没有“type”,那么“info”数组应该有空/空值。
答案 0 :(得分:2)
使用_.mapValues
通过密钥访问来迭代对象值
var res = _.chain(array1)
.concat(array2)
.groupBy('type')
.mapValues(function(val, key) {
return {
type: key,
info: val
};
})
.values()
.value();
答案 1 :(得分:1)
可以在javascript中实现您想要的结果,或者使用像lodash这样的帮助器。 你问题的最后一部分很难理解。如果数组没有"键入",您将如何对它们进行分组。请提供更清晰的解释或修改您的预期输入和输出。
[更新] 谢谢你的解释。这是使用普通javascript的解决方案。
// get uniques type from two arrays
const uniqueTypes = new Set(array1
.concat(array2)
.map(x => x.type));
// loop the types, find item in both array
// group it
let result = Array.from(uniqueTypes).reduce((acc, curr) => {
const item1 = array1.find(x => x.type === curr);
const item2 = array2.find(x => x.type === curr);
const info1 = item1 ? [item1] : [];
const info2 = item2 ? [item2] : [];
acc = acc.concat({ type: curr, info: [info1, info2] });
return acc;
}, []);
console.log(result);
答案 2 :(得分:1)
这是一个有效的解决方案:)。希望它有所帮助!
var array1 = [
{
"type":"test",
"name":"name1"
},
{
"type":"dev",
"name":"name2"
}
]
var array2 = [
{
"type":"test",
"name":"name3"
},
{
"type":"dev",
"name":"name4"
},
{
"type":"prod",
"name":"name5"
}
]
var newArray = array1.concat(array2);
var arr1 = [];
var arr2 = [];
var arr3 = [];
var arrTypes = [];
var finalArray = [];
var someArray = [];
for(var i in newArray)
{
if (arrTypes.indexOf(newArray[i].type) === -1){
arrTypes.push(newArray[i].type);
}
if(newArray[i].type === "test"){
arr1.push(newArray[i]);
}
else if(newArray[i].type === "dev"){
arr2.push(newArray[i]);
}
else if(newArray[i].type === "prod"){
arr3.push(newArray[i]);
}
}
someArray.push(arr1);
someArray.push(arr2);
someArray.push(arr3);
for(var j = 0; j < someArray.length; j++){
finalArray.push({
"type": arrTypes[j],
"info": someArray[j]
});
}
console.log(finalArray);
&#13;
答案 3 :(得分:0)
一个简短的(不可读的?)ES6解决方案:
Array#Map
类型/信息对象的条目数组
const array1 = [{"type":"test","name":"name1"},{"type":"dev","name":"name2"}];
const array2=[{"type":"test","name":"name3"},{"type":"dev","name":"name4"},{"type":"prod","name":"name5"}];
const result = [...array1.concat(array2).reduce((r, o) => {
r.has(o.type) ? r.get(o.type).push(o) : r.set(o.type, [o]);
return r;
}, new Map).entries()]
.map(([type, info]) => ({
type, info
}));
console.log(result);
&#13;