transaction =[
{
"details": [
{
"type": "1",
},
{
"type": "2",
}
],
"list": {
"number": "30",
}
},
{
"details": [
{
"type": "3",
},
{
"type": "4",
}
],
"list": {
"number": "30",
}
}
]
循环组合2个数组后的预期输出:
{
"details": [
{
"type": "1",
},
{
"type": "2",
},
{
"type": "3",
},
{
"type": "4",
}
]
}
有没有办法检查第二个数组是否存在,然后在循环中连接第二个数组。我尝试使用map循环和迭代,并在数组列表中连接任何建议,谢谢
map((activity:{ details: any; list: any; }) => {
const data = activity.details!.concat(activity
.filter((activity) => activity.details.includes(activity.details)));
console.log(data);
})
最佳答案
您可以使用reduce()
和spread运算符来创建组合的1D数组。通过使用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)
关于javascript - 如何使用Javascript循环和连接第二个数组列表(如果存在),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60569558/