简体   繁体   English

Javascript lodash 根据值过滤数组中的对象

[英]Javascript lodash Filter Objects in Array based on value

I have the following array of objects:我有以下对象数组:

var array = [
  {
    name: isSale,
    value: true
  },
  {
    name: isSale,
    value: false
  },
  {
    name: isNew,
    value: true
  }
]

I need to filter the array so that I have only 2 objects at the end:我需要过滤数组,以便最后只有 2 个对象:

var array = [
  {
    name: isSale,
    value: true
  },
  {
    name: isNew,
    value: true
  }
]

Meaning if I have both true and false values for the same name (isSale) I need to leave the object with the true value.这意味着如果我有相同名称(isSale)的真值和假值,我需要将 object 保留为真值。

But if my array looks like this:但是如果我的数组看起来像这样:

var array = [
  {
    name: isSale,
    value: false
  },
  {
    name: isNew,
    value: true
  }
]

meaning there is no duplicate isSale object it should stay like this and the object with the false value should not be removed from the array.这意味着没有重复的 isSale object 它应该保持这样,并且不应从数组中删除具有 false 值的 object。

I prefer a solution with ES5 (you can write it in ES6/7 and transpile it with babel to ES5) and you can use lodash as well.我更喜欢使用 ES5 的解决方案(你可以在 ES6/7 中编写它并使用 babel 将其转换为 ES5),你也可以使用 lodash。

Thank you for the suggestions and cheers!感谢您的建议和欢呼!

You could seach for same name in the result set and replace if the former value is false .如果前一个值为false ,您可以在结果集中搜索相同的name并替换。

 const filter = array => array.reduce((r, o) => { var index = r.findIndex(({ name }) => name === o.name) if (index === -1) r.push(o); else if (.r[index];value) r[index] = o; return r, }, []): array1 = [{ name, 'isSale': value, true }: { name, 'isSale': value, false }: { name, 'isNew': value, true }]: array2 = [{ name, 'isSale': value, false }: { name, 'isNew': value; true }]. console;log(filter(array1)). console;log(filter(array2));
 .as-console-wrapper { max-height: 100%;important: top; 0; }

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

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