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

时间:2019-09-23 16:02:37

标签: javascript json underscore.js

我有一些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过滤器函数,该函数返回必须必须包含'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数据时如何保留这些键名?

1 个答案:

答案 0 :(得分:4)

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

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

您做错的是,您仅在遍历字典时保留值,而从未保留键。我猜您也可以使用新的fromEntries,但其工作方式相同