简体   繁体   中英

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

I want to return array with properties which not matched by valuesToCompare array values

 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"]

expected output

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

I'm not sure whether you want to match or exclude based on an array of values, so providing both:

 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)

You could do like below:

  • group the arr by name
  • with each grouped, filter the value
  • flatten each group back into objects

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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