猿问

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

我想返回具有与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"},

]


慕工程0101907
浏览 111回答 2
2回答

杨__羊羊

我不确定您是否想要根据值数组进行匹配或排除,因此请提供两者: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)

MM们

你可以像下面这样做:分组arr依据name对于每个分组,过滤值将每个组展平为对象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; }
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答