如何按值过滤JavaScript对象?

时间:2018-09-01 06:42:09

标签: javascript ecmascript-6

我有一个标准化的对象,例如:

const raw = {
  1: { foo: 1, bar: 1, flag: 0 },
  4: { foo: 4, bar: 4, flag: 1 },
  11: { foo: 11, bar: 11, flag: 0 },
  ...
}

我想删除具有flag: 1的值。

{
  1: { foo: 1, bar: 1, flag: 0 },
  11: { foo: 11, bar: 11, flag: 0 },
  ...
}

我如何一成不变地做到这一点?

3 个答案:

答案 0 :(得分:6)

您可以使用Object.values()Array.prototype.filter()

var obj = {
  1: { foo: 1, bar: 1, flag: 0 },
  2: { foo: 2, bar: 2, flag: 1 },
  3: { foo: 3, bar: 3, flag: 0 }
}
var newobj = Object.assign({}, Object.values(obj).filter(o => o.flag != 1));
console.log(newobj);

您可以使用reduce()来保留密钥:

var obj = {
  1: { foo: 1, bar: 1, flag: 0 },
  2: { foo: 2, bar: 2, flag: 1 },
  3: { foo: 3, bar: 3, flag: 0 }
}
var newobj = Object.keys(obj).reduce((a,c) => {
  if(obj[c].flag != 1) 
   a[c] = obj[c]; return a;
},{});
console.log(newobj);

答案 1 :(得分:1)

您可以通过lodashjs进行对象过滤。 https://lodash.com/docs/#filter

_.filter(obj, o => !o.flag);

答案 2 :(得分:1)

您可以使用Object.keys().reduce()方法:

let data = {
  1: { foo: 1, bar: 1, flag: 0 },
  2: { foo: 2, bar: 2, flag: 1 },
  3: { foo: 3, bar: 3, flag: 0 }
};

let result = Object.keys(data).reduce((a, c) => {
  if(data[c].flag !== 1)
    a[c] = Object.assign({}, data[c]);
  
  return a;
}, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

相关问题