Search code examples
javascriptobject

How can I remove some objects contains on a js object according to a specified property?


I have an object js that contains other objects like this :

const USER: {
        LANGUAGE: { 
            'editable': 1,
            'decimal': 0,
            'degree': 0,
            'master': 1,
            0: ['', '', 0],  
            1: ['', '', 1], 
        },
        LUM: { 
            'editable': 1,
            'decimal': 0,
            'degree': 0,
            'master': 0,
            0: ['', '', 0], 
            1: ['', '', 1], 
            2: ['', '', 2], 
        },
        SP: { 
            'editable': 1,
            'decimal': 0,
            'degree': 0,
            'master': 1,
            0: ['', '', 0], 
            1: ['', '', 1], 
            2: ['', '', 2], 
        },
    },
};

I want to create another object that contains only object which contains 'master': 1;

How can I do that?


Solution

  • You can try the following solutions:

    const filteredObjects = {};
    
    for (const key in USER) {
        if (USER[key]['master'] === 1) {
            filteredObjects[key] = USER[key];
        }
    }
    
    console.log(filteredObjects);
    

    or the approach using Object.keys and the array methods filter and reduce.

    const filteredObjects = Object.keys(USER)
        .filter(key => USER[key]['master'] === 1)
        .reduce((result, key) => {
            result[key] = USER[key];
            return result;
        }, {});
    
    console.log(filteredObjects);