这是我的数据
let a = [
{
"activityCode": "23",
"isValid": null
},
{
"activityCode": "28",
"isValid": null
},
{
"activityCode": "32",
"isValid": null
}
]
let b = [
{
"activityCode": "23",
"allocated": 3
},
{
"activityCode": "32",
"allocated": 2
}
]
我想更改"isValid"如果数组中的activityCode(a)具有相同的activityCode(b) &"isValid"如果数组中的activityCode(a)与activityCode(b)不相同,则为false,并且我需要的输出如下:
let a = [
{
"activityCode": "23",
"isValid": true
},
{
"activityCode": "28",
"isValid": false
},
{
"activityCode": "32",
"isValid": true
}
]
请帮帮我。谢谢。
试试这个:
a.forEach(element => {
element.isValid = b.some(e => e.activityCode === element.activityCode);
});
console.log(a);
a.map(aa => {
const match = b.find(bb => bb.activityCode === aa.activityCode);
return { activityCode: aa.activityCode, isValid: match !== undefined };
})
您可以使用Array.map()
和Array.some()
来获得所需的结果。如果数组b中存在a中的任何元素array .some()将返回true。
let a = [ { "activityCode": "23", "isValid": null }, { "activityCode": "28", "isValid": null }, { "activityCode": "32", "isValid": null } ]
let b = [ { "activityCode": "23", "allocated": 3 }, { "activityCode": "32", "allocated": 2 } ]
const result = a.map(({ activityCode }) => ({ activityCode, isValid: b.some(el => el.activityCode === activityCode ) }));
console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; top: 0; }