Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 equivalent to lodash _.mapValues

What are the different ways to convert the lodash _.mapValues to ES6.

Code:

var fruits= {
  'apple':    { 'name': 'apple',    'number': 5},
  'orange': { 'name': 'orange', 'number': 10 }
};

_.mapValues(fruits, 'number');

Output:

{ 'apple': 5, 'orange': 10 }
like image 330
aadhira Avatar asked Jul 18 '18 05:07

aadhira


2 Answers

reduce the entries of the object into another object, extracting only the number from the value:

var fruits= {
  'apple':    { 'name': 'apple',    'number': 5},
  'orange': { 'name': 'orange', 'number': 10 }
};

console.log(Object.entries(fruits)
  .reduce((a, [key, { number }]) => {
    a[key] = number;
    return a;
  }, {}
));

In newer environments, you can make it even more elegant by using Object.fromEntries instead, to map to an array of key-value pair arrays:

var fruits= {
  'apple':    { 'name': 'apple',    'number': 5},
  'orange': { 'name': 'orange', 'number': 10 }
};

console.log(Object.fromEntries(
  Object.entries(fruits).map(([key, { number }]) => [key, number])
));
like image 102
CertainPerformance Avatar answered Oct 06 '22 04:10

CertainPerformance


You can use for..in loop and add the key and value from old object to new object

var fruits = {
  'apple': {
    'name': 'apple',
    'number': 5
  },
  'orange': {
    'name': 'orange',
    'number': 10
  }
};

let newObj = {};

for (let keys in fruits) {
  newObj[keys] = fruits[keys].number;
}

console.log(newObj)
like image 34
brk Avatar answered Oct 06 '22 02:10

brk