如何过滤对象数组并保留对象键名?

How do I filter through an array of object and retain the object key name?

我有一些 JSON 数据,我试图在其中过滤掉没有特定 属性.

的 JSON 对象

我可以使用 filter function from Underscore.JS 成功过滤掉不正确 属性 的对象。

但是,当过滤函数运行时,它正在剥离对象的键名。

下面是过滤函数中变量data中使用的JSON:

{
    "Presentations": {
        "Instant": false,
        "Daily": false,
        "WeeklySummary": false,
        "ContentTypeId": 5
    },
    "Articles": {
        "Instant": true,
        "Daily": false,
        "WeeklySummary": true,
        "ContentTypeId": 1
    },
    "Blogs": {
        "Instant": true,
        "Daily": false,
        "WeeklySummary": true,
        "ContentTypeId": 61
    },
    "NewsBriefs": {
        "Instant": false,
        "Daily": false,
        "WeeklySummary": false,
        "ContentTypeId": 2
    },
    "SpecialInsights": {
        "Instant": false,
        "Daily": false,
        "WeeklySummary": false,
        "ContentTypeId": 50
    },
    "UserSelected": {
        "Frequency": null,
        "Value": false,
        "ContentTypeId": 0
    }
}

这是返回对象数组的 JavaScript 过滤器函数,必须 包含 属性 of 'Instant'

newArr = _.filter(data, function(obj){
              return obj.hasOwnProperty('Instant')
          });

如果我 console.log newArr,这就是我得到的:

[
   {
      "Instant":false,
      "Daily":false,
      "WeeklySummary":false,
      "ContentTypeId":5
   },
   {
      "Instant":true,
      "Daily":false,
      "WeeklySummary":true,
      "ContentTypeId":1
   },
   {
      "Instant":true,
      "Daily":false,
      "WeeklySummary":true,
      "ContentTypeId":61
   },
   {
      "Instant":false,
      "Daily":false,
      "WeeklySummary":false,
      "ContentTypeId":2
   },
   {
      "Instant":false,
      "Daily":false,
      "WeeklySummary":false,
      "ContentTypeId":50
   }
]

如您所见,它正确地过滤掉了没有 Instant 属性 的对象,在本例中是 UserSelected 对象。

但是,在那个过程中,我丢失了对象键名称,例如 PresentationsArticles

如何在过滤 JSON 数据时保留这些键名?

你可以在没有任何库的情况下做到这一点:

Object.entries(data).filter(([key, value]) => {
  return value.hasOwnProperty('Instant')
}).reduce((acc, [key, value]) => {
  return { ...acc, [key]: value }
}, {})

你做错的是你在遍历字典时只保留了值,而没有保留键。我猜你也可以使用新的 fromEntries,但它的工作方式相同