skip to Main Content

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?

4

Answers


  1. JavaScript has the methods Object.keys() and Array.reduce() which you can use to filter the objects based on their properties:

    const filteredUser = Object.keys(USER).reduce((acc, key) => {
        if (USER[key].master === 1) {
            acc[key] = USER[key];
        }
        return acc;
    }, {});
    
    console.log(filteredUser);
    
    Login or Signup to reply.
  2. 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);
    
    Login or Signup to reply.
  3. An one-liner with Object.entries():

    console.log(Object.entries(USER).reduce((r, [key, item]) => (item.master === 1 && (r[key] = item), r), {}));
    <script>
    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], 
            },
        };
    </script>

    If you want more speed, remove the destructuring:

    Cycles: 10000000 / Chrome/116
    --------------------------------------------------------------------
    Object.entries() no destructuring :  390/min  390  432  421
    Object.entries()                  :  432/min 1.1x  432  458  445
    Object.keys()                     :  469/min 1.2x  469  477  479
    Dimava                            :  1682/min 4.3x  1726  1706  1682
    --------------------------------------------------------------------
    https://github.com/silentmantra/benchmark
    
    <script benchmark="10000000">
    
        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], 
                },
            };
    
    // @benchmark Object.keys()
    Object.keys(USER).reduce((r, key) => (USER[key].master === 1 && (r[key] = USER[key]), r), {});
    
    // @benchmark Object.entries()
    Object.entries(USER).reduce((r, [key, item]) => (item.master === 1 && (r[key] = item), r), {});
    
    // @benchmark Object.entries() no destructuring
    Object.entries(USER).reduce((r, entry) => (entry[1].master === 1 && (r[entry[0]] = entry[1]), r), {});
    
    // @benchmark Dimava
    function objectFilter(obj, filter) {
      return Object.fromEntries(
        Object.entries(obj)
          .filter(([key, value]) => filter(value, key, obj)),
      )
    }
    
    // @run
    objectFilter(USER, (e) => e.master === 1)
    
    </script>
    <script src="https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js"></script>
    Login or Signup to reply.
  4. /**
     * Works the same as array.filter, but with an object
     * @template O
     * @param {O} obj
     * @param { (e: O[keyof O], k: keyof O, o: O) => boolean } filter
     * @returns { Partial<O> }
     */
    function objectFilter(obj, filter) {
      return Object.fromEntries(
        Object.entries(obj)
          .filter(([key, value]) => filter(value, key, obj)),
      )
    }
    
    console.log(objectFilter(USER, (e) => e.master === 1))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search