【问题标题】:Delete object with certain key value from filtering array of objects从过滤对象数组中删除具有特定键值的对象
【发布时间】:2020-08-28 15:28:45
【问题描述】:

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

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


})

具有“category_id: 4”的对象没有“选项”,但在 filter 内我需要所有存在的选项值:

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

})

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

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

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

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

我真的放弃了。请帮忙。

【问题讨论】:

  • 在获取值之前检查options是否存在。例如,const tOptinos = t.options ? Object.values(t.options) : [];.

标签: javascript arrays object filtering


【解决方案1】:

也许你可以尝试复制对象测试使用 (.. 你的对象) 或 array.splice(index, number of elements, element, element) 或 slice() 祝你好运

【讨论】:

    【解决方案2】:

    添加一个 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;
      }
    });
    ``
    
    

    【讨论】:

    • 你完全正确!谢谢,我想我太努力想解决这个问题了=)
    猜你喜欢
    • 1970-01-01
    • 2018-09-26
    • 1970-01-01
    • 2019-02-09
    • 2021-10-26
    • 2022-07-02
    • 1970-01-01
    • 1970-01-01
    • 2022-07-12
    相关资源
    最近更新 更多