繁体   English   中英

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

[英]How to change value for object property in array if property not match with compared value?

我想返回与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"]

预计 output

[
{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; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM