JS ES6 Correct way to filter object by array of keys

后端 未结 4 663
旧时难觅i
旧时难觅i 2021-01-26 21:57

I would like to take an array of objects and filter each object to only return the properties where the key matches an item in an array.

For example:

con         


        
相关标签:
4条回答
  • 2021-01-26 22:15

    You could map the wnated entries and builds objects with it.

    const 
        keys = ['key_1', 'key_3'],
        data = [{ key_1: 'Some Value A', key_2: 'Some Other Value A', key_3: 'Some Final Value A' }, { key_1: 'Some Value B', key_2: 'Some Other Value B', key_3: 'Some Final Value B' }, { key_1: 'Some Value C', key_2: 'Some Other Value C', key_3: 'Some Final Value C' }],
        result = data.map(o => Object.fromEntries(keys.map(k => [k, o[k]])));
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    0 讨论(0)
  • 2021-01-26 22:17

    You can .map each object to its entries so you can .filter out any entries which don't have a key in myKeys, and then use .fromEntries() to build up your new object like so:

    const myKeys = ['key_1', 'key_3'];
    const myArray = [{
        key_1: 'Some Value A',
        key_2: 'Some Other Value A',
        key_3: 'Some Final Value A',
      },
      {
        key_1: 'Some Value B',
        key_2: 'Some Other Value B',
        key_3: 'Some Final Value B',
      },
      {
        key_1: 'Some Value C',
        key_2: 'Some Other Value C',
        key_3: 'Some Final Value C',
      },
    ];
    
    const res = myArray.map(obj => Object.fromEntries(Object.entries(obj).filter(([k, v]) => myKeys.includes(k))));
    
    console.log(res);

    0 讨论(0)
  • 2021-01-26 22:21

    const myKeys    = ['key_1', 'key_3'];
    const myArray   = [
    	{
    		key_1: 'Some Value A',
    		key_2: 'Some Other Value A',
    		key_3: 'Some Final Value A',
    	},
    	{
    		key_1: 'Some Value B',
    		key_2: 'Some Other Value B',
    		key_3: 'Some Final Value B',
    	},
    	{
    		key_1: 'Some Value C',
    		key_2: 'Some Other Value C',
    		key_3: 'Some Final Value C',
    	},
    ];
    
    const result = myArray.map(i => Object.fromEntries(Object.entries(i).filter(([k]) => myKeys.includes(k))));
    
    console.log(result);

    0 讨论(0)
  • 2021-01-26 22:36

    You can simply loop over keys and build a new object which contains only those keys and respective values

    const myKeys = ['key_1', 'key_3'];
    const myArray = [{key_1: 'Some Value A',key_2: 'Some Other Value A',key_3: 'Some Final Value A',},{key_1: 'Some Value B',key_2: 'Some Other Value B',key_3: 'Some Final Value B',},{key_1: 'Some Value C',key_2: 'Some Other Value C',key_3: 'Some Final Value C',},];
    
    let final = myArray.map(v => {
      return myKeys.reduce((op, key) => {
        op[key] = v[key]
        return op
      }, {})
    })
    
    console.log(final)

    0 讨论(0)
提交回复
热议问题