JS如何在forEach循环中从数组中删除对象?

时间:2019-02-20 05:55:52

标签: javascript arrays object ecmascript-6

我有一个data对象,其内容如下:

{
  "content": {
    "id": "someID",
    "type": "unit",
    "method": "xyz",
    "blocks": [{
      "key": "blue",
      "data": [
        "Array"
      ]
    }, {
      "key": "red",
      "data": [
        "Array"
      ]
    }, {
      "key": "yellow",
      "data": [
        "Array"
      ]
    }, {
      "key": "black",
      "data": [
        "Array"
      ]
    }],
    "notes": "abc"
  }
}

我想通过循环block来删除具有键yellow的{​​{1}},其余数据应保留原样。因此预期的最终结果将是

blocks

数据是动态的,所以我不知道会返回什么,它可能符合我的条件,也可能不匹配。

我尝试了很多方法,但到目前为止似乎没有任何效果。如果更方便,我也可以使用{ "content": { "id": "someID", "type": "unit", "method": "xyz", "blocks": [{ "key": "blue", "data": [ "Array" ] }, { "key": "red", "data": [ "Array" ] }, { "key": "black", "data": [ "Array" ] }], "notes": "abc" } } 。这些似乎都不起作用。任何帮助/方向表示赞赏

lodash

1 个答案:

答案 0 :(得分:6)

您只需要filter

const obj = {
  "content": {
    "id": "someID",
    "type": "unit",
    "method": "xyz",
    "blocks": [{
      "key": "blue",
      "data": [
        "Array"
      ]
    }, {
      "key": "red",
      "data": [
        "Array"
      ]
    }, {
      "key": "yellow",
      "data": [
        "Array"
      ]
    }, {
      "key": "black",
      "data": [
        "Array"
      ]
    }],
    "notes": "abc"
  }
};
obj.content.blocks = obj.content.blocks.filter(({ key }) => key !== 'yellow');
console.log(obj);