我有两个具有动态值的数组,在这里我需要将arrayA1-> KEY与arrayA2-> ID和nestedArray-> ID进行比较,将arrayA1的值分配给arrayA2的嵌套数组,并以与arrayA2相同的格式返回该数组。
这里每个对象的arrayA1中的最后一个键需要分配或与arrayA2-> ID进行比较,剩余的值需要与arrayA1的各个对象的arrayA2的nestedArray进行关联,如果在ID匹配arrayA1键的情况下,则在nestedArray中分配该值。 arrayA1的值传递给nestedArray“isVerificationMet”。
下面是arrayA1:
arrayA1 = [{
13928: false,
13932: true,
13935: true,
13995: false,
},
{
13927: true,
14024: false,
},
{
13906: false,
13935: true,
13928: true,
14029: false,
}
]
这是arrayA2:-
arrayA2 = [{
id: 13995,
nestedArray: [{
id: 13928,
isVerificationMet: false
},
{
id: 13932,
isVerificationMet: false
},
{
id: 13935,
isVerificationMet: false
},
]
},
{
id: 14024,
nestedArray: [{
id: 13927,
isVerificationMet: false
}, ]
},
{
id: 14029,
nestedArray: [{
id: 13906,
isVerificationMet: false
},
{
id: 13935,
isVerificationMet: false
},
{
id: 13928,
isVerificationMet: false
},
]
}
]
这是arrayA2(result)的最终o / p。
result = [{
id: 13995,
nestedArray: [{
id: 13928,
isVerificationMet: false
},
{
id: 13932,
isVerificationMet: true
},
{
id: 13935,
isVerificationMet: true
},
]
},
{
id: 14024,
nestedArray: [{
id: 13927,
isVerificationMet: true
}, ]
},
{
id: 14029,
nestedArray: [{
id: 13906,
isVerificationMet: false
},
{
id: 13935,
isVerificationMet: true
},
{
id: 13928,
isVerificationMet: true
},
]
}
]
}
这是我正在尝试的逻辑,它不起作用,
const docDetails = arrayA2.map((item, i) => {
const A2 = Object.assign({}, item);
const keys = Object.keys(arrayA1[i]);
keys.forEach(key => {
if (A2.id == parseInt(key)) {
A2.id = parseInt(key)
}
const fieldList1 = item.nestedArray.filter(elem => {
const A1 = Object.assign({}, elem);
if (parseInt(key) == A1.id) {
A1.isVerificationMet = arrayA1[i][key];
}
return A1;
});
return (A2.fieldList = fieldList1);
});
})
上面的逻辑变得笨拙,我尝试了其他所有方式,使它循环了很多次,并且没有分配正确的值。
在这里我使用了object.assign,因为arrayA2是只读的。
最佳答案
您可以找到带有值的对象并映射新对象。
const
arrayA1 = [{ 13928: false, 13932: true, 13935: true, 13995: false }, { 13927: true, 14024: false }, { 13906: false, 13935: true, 13928: true, 14029: false }],
arrayA2 = [{ id: 13995, nestedArray: [{ id: 13928, isVerificationMet: false }, { id: 13932, isVerificationMet: false }, { id: 13935, isVerificationMet: false }] }, { id: 14024, nestedArray: [{ id: 13927, isVerificationMet: false }] }, { id: 14029, nestedArray: [{ id: 13906, isVerificationMet: false }, { id: 13935, isVerificationMet: false }, { id: 13928, isVerificationMet: false }] }],
result = arrayA2.map(({ id, nestedArray }) => ({
id,
nestedArray: nestedArray.map(o => ({
...o, isVerificationMet: arrayA1.find(q => id in q)?.[o.id]
}))
}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 将嵌套数组与另一个数组进行比较,并指定值是否相同,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/63434993/