我有两个数组,下面有数据,我需要更改第一个数组中的状态以获取arr2中的所有状态而无需重复我提供了一个示例,但这根本不够用
const arr1 = [{ agentId: 1234, state: "CA" }];
const arr2 = [{ agentId: 1234, AK: "c", AL: "N", CA: "c" }];
var res = [];
arr1.forEach((x) => {
arr2.forEach((y) => {
if (x.agentId === y.agentId) {
for (const [key, value] of Object.entries(y)) {
if (value === "c") {
x.state += " ," + key;
}
}
}
});
});
结果应该是这样的
arr1 = [{ agentId: 1234, state: "CA, AK" }]
您可以使用Set
来确保唯一性:
const arr1 = [
{ agentId: 1234, state: "CA" },
{ agentId: 4567, state: "FL" }
];
const arr2 = [
{ agentId: 1234, AK: "c", AL: "N", CA: "c" },
{ agentId: 4567, AK: "N", AL: "c", FL: "c" }
];
for (const x of arr1) {
const states = new Set([x.state]);
for (const y of arr2) {
if (x.agentId === y.agentId) {
for (const [key, value] of Object.entries(y)) {
if (value === "c") {
states.add(key);
}
}
break;
}
}
x.state = [...states].join(", ");
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句