为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕工程0101907 2024-01-18 14:35:44
我想返回具有与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"},]
查看完整描述

2 回答

?
杨__羊羊

TA贡献1943条经验 获得超7个赞

我不确定您是否想要根据值数组进行匹配或排除,因此请提供两者:


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)


查看完整回答
反对 回复 2024-01-18
?
MM们

TA贡献1886条经验 获得超2个赞

你可以像下面这样做:

  • 分组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; }


查看完整回答
反对 回复 2024-01-18
  • 2 回答
  • 0 关注
  • 110 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信