Search code examples
javascriptarraysecmascript-6javascript-objects

Filter Object in ES6 to form another Object


I have an array of objects like below, am trying to map only certain keys and their values to form another object of array.

Below is my attempt with a single object

const object1 = { app_id:35687,codesmell: 30, baz: 42 };
console.log(Object.entries(object1).map(x => {app_id:x.app_id}));

I always get undefined, have been searching through mdn and stackoverflow couldnt find a solution. Please help.

Another attempt i tried, this time with arrays where result is an array of objects

T_BugDetails: result.data.map(x => Object.entries(x).reduce((a,b) => { a, b},{}))

Solution

  • Some problems:

    • Object.entries returns an array of arrays (an array of the keys and values of the object). If you .map the entries of an object, the first argument to .map should be an array of the key and value, like this:

      Object.entries(object1).map(([key, val]) => ...
      
    • To return an object from an arrow function, enclose the object's brackets ({ and }) in parentheses, else it will be interpreted as a plain function block with a label inside, rather an object to be implicitly returned:

      => {app_id:x.app_id}
      

    to

        => ({app_id:x.app_id})
    
    • But if you just want an object composed of the app_id of the original object, don't iterate over the entries of the original object, since you only want one property, not all of its properties - instead, just extract the app_id of the original object:

    const object1 = { app_id:35687,codesmell: 30, baz: 42 };
    const { app_id } = object1;
    console.log(
      { app_id }
    );

    You would use .map only if you have an array of objects you need to transform, for example:

    const objects = [
      { app_id:35687,codesmell: 30, baz: 42 },
      { app_id:12345,codesmell: 20, baz: 52 }
    ];
    console.log(
      objects.map(({ app_id }) => ({ app_id }))
    );