从筛选对象数组中删除具有特定键值的对象

时间:2020-05-12 17:05:20

标签: javascript arrays object filtering

我有一个对象数组并对其进行过滤:

func configureAction(type: FieldTypeEnum) {
 let isNotNull = (sender as AnyObject).imageView?.image != nil
        reference.setValue(isNotNull)
        reference = Database.database().reference().child("check").child(keyword!).child("prayCheck")
        let image: UIImage? = isNotNil ? UIImage(named: "check") : nil
        cell.prayButton.setImage(image, for: .normal)
}

带有“ category_id:4”的对象没有“选项”,但是在const test = [ { "id":2, "category_id":1, "features":["blah","blah","blah","blah"], "options": { "option1": { "b":22,"c":105,"d":70,"e":345 }, "option2": { "c":25,"c":41,"d":70,"e":345 } } }, { "id":4, "category_id":2, "features":["blah","blah","blah","blah"], "options": { "option1": { "b":22,"c":105,"d":70,"e":345 }, "option2": { "c":25,"c":41,"d":70,"e":345 } } }, { "id":7, "category_id":4, "features":null, "options":null }, { "id":11, "category_id":6, "features":["blah","blah","blah","blah"], "options": { "option1": { "b":22,"c":105,"d":70,"e":345 }, "option2": { "c":25,"c":41,"d":70,"e":345 } } } ] const filtered = test.filter((t) => { }) 内,我需要存在的所有选项值:

filter

它给我一个错误,因为某些选项不存在。 我知道如何修改数组和删除不带选项的对象(使用Lodash)

const filtered = test.filter((t) => {
  const tOptions = Object.values(t.options)

})

但是由于后面的逻辑,我无法修改“测试”数组。 不知何故,我需要这个结果而不接触数组本身:

_.reject(test, function(el) { return el.category_id === 4 })

我真的放弃了。请帮忙。

2 个答案:

答案 0 :(得分:0)

添加一个if条件,以检查t.options是否不为空

const filtered = test.filter((t) => {
  if(t.options) { // null and undefined are falsey
     const tOptions = Object.values(t.options);

  } else {
      return false;
  }
});
``

答案 1 :(得分:0)

也许您可以尝试复制对象测试使用(..您的对象)或array.splice(索引,元素数,元素,元素)或slice()祝您好运