我可以在嵌套映射中获取相同值的值。但如何获得两者之间的差异呢?
我尝试了 map 、过滤器,但我不知道如何正确删除重复值。
const responseData = [
{ value: "red", label: "Red" },
{ value: "blue", label: "Blue" }
];
const fixedColors = [
{ value: "red", label: "Red" },
{ value: "blue", label: "Blue" },
{ value: "yellow", label: "Yellow" },
{ value: "orange", label: "Orange" }
];
responseData.map(opt => {
fixedColors.findIndex(obj => {
if (obj.value === opt.value) {
testArray.push(opt);
} else {
testArray2.push(obj);
}
});
});
我可以在两个数组上获得相同的值,但我无法得到差异。我不知道如何使用 ES6 正确执行它。
最佳答案
过滤
您的响应,仅包含尚未包含在fixedColors
中的值,并将结果与fixedColors
concat
const responseData = [{value: "purple", label:"Purple is new"}, {value: "blue", label:"Blue"}]
const fixedColors = [{value: "red", label:"Red"}, {value: "blue", label:"Blue"},{value: "yellow", label:"Yellow"}, {value: "orange", label:"Orange"}]
const existingValues = fixedColors.map(x => x.value)
const valuesToAdd = responseData.filter(x => !existingValues.includes(x.value))
const newValues = fixedColors.concat(valuesToAdd)
console.log(newValues)
关于javascript - 如何删除重复项并计算两个数组之间的差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58397164/