ES6 equivalent to lodash _.mapValues
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)
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])
));