SBT23434
SBT23434

Reputation: 185

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

I have some JSON data where I am attempting to filter out JSON objects that do not have a specific property.

I am able to use a filter function from Underscore.JS to successfully filter out the objects that do not have the correct property.

However, when the filter function runs, it is stripping out the key name of the object.

Here is the JSON that is used in the variable data in the filter function below:

{
    "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
    }
}

Here is the JavaScript filter function that is returning an array of objects that must include a property of 'Instant'

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

If I console.log the newArr, here is what I get:

[
   {
      "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
   }
]

As you can see, it is correctly filtering out objects that do not have the Instant property which in this case is the UserSelected object.

However, in that process I am losing the Object key names like Presentations and Articles.

How do I retain these key names when filtering the JSON data?

Upvotes: 0

Views: 976

Answers (1)

grokked
grokked

Reputation: 411

you can do it without any library:

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

what you did wrong was that you only kept the value while iterating over the dictionary, but never carried over the keys. You can also use the new fromEntries I guess, but it works the same way

Upvotes: 4

Related Questions