Search code examples
javascriptarraysjsonunderscore.jsjavascript-objects

How can I set all the properties of an array of objects to true?


I have some JSON data that I am attempting to map over and set all the properties to true.

I am aware that you can use the map function for this, however the way that the JSON is set up, each of the objects in the array has a key name.

So when I run the map function, it's setting all of the key names to false rather than the properties inside of the object itself.

Here is the JSON Data:

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

Here is the map function I attempted, where data refers to the JSON above:

Object.entries(data).map(([key, value]) => {
     return value === true;
});

This in turn returns an array of five items with the value false:

[false,false,false,false,false]

What I am attempting to do is flip the values of any items that is false to true.


Solution

  • You can simply do this using nested forEach as well, like this -

        const a = {
          "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
        }
    }
        
        Object.keys(a).forEach(ele => {
        	Object.keys(a[ele]).forEach(childEle => {a[ele][childEle] = true});
        })
        
        console.log(a);