Search code examples
javascriptarraysobjectmappingjavascript-objects

push special elements of array of objects to another array of objects


i have an large array of objects full of values and i have an empty array of objects as well, and i am willing to get every value from full array of objects (btw full array of objects has more keys than empty one) and push it to empty one like so:

/*empty one (array1):*/ [{foo: '', bar: '', thumbnail: ''}];

/*full one (array2):*/ [{foo_: 'blah', bar: 'blah',
                       thumbnail: '/photo', id: 'ad12dxa1', something: 'thing'},{foo_: 'blah1', bar: 'blah1',
                       thumbnail: '/photo1', id: 'ad12dxa12', something: 'thing1'}];

and i want to get only foo_, bar and thumbnail from array2 and insert them as foo, bar & thumbnail into array1 like: foo = foo_ bar=bar, thumbnail= thumbnail

if answer will include both for loop and array.every method explanation it would be better.

Thank you!


Solution

  • You can simply create a new array using .map() with some Object Destructuring:

    const data = [
      {foo_: 'blah', bar: 'blah', thumbnail: '/photo', id: 'ad12dxa1', something: 'thing'},
      {foo_: 'blah1', bar: 'blah1', thumbnail: '/photo1', id: 'ad12dxa12', something: 'thing1'}
    ];
                                                
    const result = data.map(({foo_:foo, bar, thumbnail}) => ({foo, bar, thumbnail}));
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }