[英]How to loop and concat second array list if exist using Javascript
transaction =[
{
"details": [
{
"type": "1",
},
{
"type": "2",
}
],
"list": {
"number": "30",
}
},
{
"details": [
{
"type": "3",
},
{
"type": "4",
}
],
"list": {
"number": "30",
}
}
]
expected output after combining 2 array in a loop:在循环中组合 2 个数组后的预期输出:
{
"details": [
{
"type": "1",
},
{
"type": "2",
},
{
"type": "3",
},
{
"type": "4",
}
]
}
Is there any way to check if second array exist and then concat the second array in a loop.I tried to loop and iterate using map and concat the array list any suggestion would be appreciated thanks有什么方法可以检查第二个数组是否存在,然后在循环中连接第二个数组。我尝试使用 map 循环和迭代并连接数组列表,任何建议将不胜感激,谢谢
map((activity:{ details: any; list: any; }) => {
const data = activity.details!.concat(activity
.filter((activity) => activity.details.includes(activity.details)));
console.log(data);
})
You can use reduce()
and spread operator to create a combined 1D array.您可以使用reduce()
和 spread 运算符来创建组合的一维数组。 Before adding the new details
array to final result filter()
by checking that all the previous types are differ using every()
在将新的details
数组添加到最终结果filter()
之前,使用every()
检查所有以前的类型是否不同
const transaction =[ { "details": [ { "type": "1", }, { "type": "2", } ], "list": { "number": "30", } }, { "details": [ { "type": "3", }, { "type": "4", } ], "list": { "number": "30", } } ] const res = transaction.reduce((ac, a) => [...ac, ...a.details.filter(x => ac.every(n => n.type !== x.type))], [] ); console.log(res)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.