【问题标题】:Filter JavaScript Array of Objects based on Objects Key根据 Objects Key 过滤 JavaScript 对象数组
【发布时间】:2021-04-03 05:31:25
【问题描述】:

我有一个从 JSON 响应生成的对象数组。

所述数组的内容结构如下:

const array = [
{title: "user generated title", message: "random user generated text", status: "Active/Inactive"},
 {200 + more objects with the exact same key/values as the first},
...,
...
]

我想用完全相同的对象减去特定的键/值对创建一个新数组。

即,制作完全相同的数组而不说出所有消息:“用户消息”键/值对。 (不过,我想从数组中的对象中删除多个键/值对。)

应该是这样的

const array = [
{title: "user generated title", status: "Active/Inactive"},
{200 + objects just like the first without the message: "message text"},
...,
...
]

【问题讨论】:

标签: javascript arrays sorting filter javascript-objects


【解决方案1】:
var newArray = [];
for (var i = 0; i < array.length; i++) {
    var obj = array[i];
    
    if (!("message" in obj)) { //put the conditions to keep the object here
        newArray.push(obj); //copy reference to new array
    }
}

【讨论】:

    【解决方案2】:

    您可以检查它们并删除这些键:

    array.forEach(o => delete o.message); 
    

    【讨论】:

      猜你喜欢
      • 2020-12-03
      • 2017-03-19
      • 1970-01-01
      • 1970-01-01
      • 2019-09-15
      • 1970-01-01
      • 1970-01-01
      • 2021-03-21
      • 2022-01-13
      相关资源
      最近更新 更多