javascriptarraysecmascript-6filterreduce

How to filter/reduce array of object with specific dynamically keys based in other array


I'm gonna explain my problem. I don't have time to think more about that and I have a blocker and I can't figure it out so any help will be appreciated. For example, I have an array of objects (it can be array with 100+ elements):

  const arr = [
    { value: '1', id: 1, number: 1, other: 'example', data: '6' },
    { value: '2', id: 2, number: 2, other: 'example', data: '7' },
    { value: '3', id: 3, number: 3, other: 'example', data: '8' },
    { value: '4', id: 4, number: 4, other: 'example', data: '9' },
    { value: '5', id: 5, number: 4, other: 'example', data: '10' },
  ];

and in the other array I have strings which contain specific keys like that:

  const keys = ['value', 'id', 'number'];

and my problem is that I want to return the variable arr only contains objects based on values on the keys variable. Something like that:

 const arr = [
    { value: '1', id: 1, number: 1 },
    { value: '2', id: 2, number: 2 },
    { value: '3', id: 3, number: 3 },
    { value: '4', id: 4, number: 4 },
    { value: '5', id: 5, number: 4 },
  ];

I would like to have it dynamically because values in the keys variable are not constant and can be a value, other, data or only data or id and other etc.


Solution

  • Create a function which will return based on keys array and use that function to map..

    const arr = [
            { value: '1', id: 1, number: 1, other: 'example', data: '6' },
            { value: '2', id: 2, number: 2, other: 'example', data: '7' },
            { value: '3', id: 3, number: 3, other: 'example', data: '8' },
            { value: '4', id: 4, number: 4, other: 'example', data: '9' },
            { value: '5', id: 5, number: 4, other: 'example', data: '10' },
          ];
    
        const keys = ['value', 'id', 'number'];
    
        function pick(obj, keys){
            let result = {};
            for(let i=0; i<keys.length; i++){
                result[keys[i]] = obj[keys[i]];
            }
            return result;
        }
    
        let finalArr = arr.map( value => pick(value,keys));
    
        console.log(finalArr);