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 }
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])
));
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With