![](/img/trans.png)
[英]Return filtered array once compared to value of object property in second array
[英]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)
你可以这样做:
name
对arr
进行分组 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.