简体   繁体   English

从过滤对象数组中删除具有特定键值的 object

[英]Delete object with certain key value from filtering array of objects

I have an array of objects and I filtering it:我有一个对象数组,我过滤它:

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) => {


})

Objects with "category_id: 4" don't have "options" but inside the filter I need all options value that exist:具有“category_id:4”的对象没有“选项”,但在filter中我需要所有存在的选项值:

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

})

it gives me an error because some options does't exist.它给了我一个错误,因为某些选项不存在。 I know how to modify an array and delete objects without options (with Lodash)我知道如何修改数组并删除没有选项的对象(使用 Lodash)

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

but I can't modify "test" array because of the logic that goes after.但由于后面的逻辑,我无法修改“测试”数组。 Somehow I need this result without touching an array itself:不知何故,我需要这个结果而不接触数组本身:

[
 Object 
 {
  b:22,
  c:105,
  d:70,
  e:345
 }, 
Object 
 {
  c:41,
  d: 70,
  e: 345
 }
]

I really give up.我真的放弃了。 Please help.请帮忙。

Add an if condition to check if t.options is not null添加 if 条件以检查 t.options 是否不是 null

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

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

maybe you can try copy object test use (.. your object) or array.splice(index, number of elements, element, element) or slice() good luck也许你可以尝试复制 object 测试使用 (.. 你的对象) 或 array.splice(index, number of elements, element, element) 或 slice() 祝你好运

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

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