如果数组中的对象属性和比较值不匹配,如何更改该属性的值



我想返回属性与valuesToCompare数组值不匹配的数组

const arr = [
{value: "test1", name: "name1"},
{value: "test2", name: "name1"},
{value: "test3", name: "name1"},
{value: "test3", name: "name2"},
{value: "test4", name: "name2"},
]
const valuesToCompare = ["test1", "test2", "test3", "test4"]

预期输出

[
{value: "test4", name: "name1"},
{value: "test1", name: "name2"},
{value: "test2", name: "name2"},
]

我不确定您是想根据值数组进行匹配还是排除,所以提供两者:

const arr = [{
value: "test1",
name: "name1"
},
{
value: "test2",
name: "name1"
},
{
value: "test3",
name: "name1"
},
{
value: "test3",
name: "name2"
},
{
value: "test4",
name: "name2"
},
]
const valuesToCompare = ["test1", "test2"]
const excluding = arr.filter(obj => !valuesToCompare.includes(obj.value))
console.log("Excluding values:")
console.log(excluding)
const matching = arr.filter(obj => valuesToCompare.includes(obj.value))
console.log("Matching values:")
console.log(matching)

您可以执行以下操作:

  • namearr进行分组
  • 对于每个分组,筛选值
  • 将每组展平为对象

const arr = [
{ value: "test1", name: "name1" },
{ value: "test2", name: "name1" },
{ value: "test3", name: "name1" },
{ value: "test3", name: "name2" },
{ value: "test4", name: "name2" },
];
const valuesToCompare = ["test1", "test2", "test3", "test4"];
const groupByName = arr.reduce((acc, el) => {
if (acc[el.name]) {
acc[el.name].push(el.value);
} else {
acc[el.name] = [el.value];
}
return acc;
}, {});
const res = Object.entries(groupByName)
.map(([k, v]) => [k, valuesToCompare.filter((vtc) => !v.includes(vtc))])
.map(([k, v]) => v.map((v) => ({ name: k, value: v })))
.flat();
console.log(res);
.as-console-wrapper { max-height: 100% !important; }

最新更新