Using es6 javascript is it possible to iterate over an object and return a new object. For example:
const people = {
'Sally': {
age: 22,
sex: 'female',
},
'John': {
age: 64,
sex: 'male',
},
'Sam': {
age: 12,
sex: 'female',
},
};
const ages = people.someEs6IteratingObjectFunction((index, person) => {
return { Object.keys(people)[index]: person.age };
});
console.log(ages); // { 'Sally': 22, 'John': 64, 'Sam': 12, }
You can use reduce method of array prototype. It also works in es5.
const people = {
'Sally': {
age: 22,
sex: 'female',
},
'John': {
age: 64,
sex: 'male',
},
'Sam': {
age: 12,
sex: 'female',
},
};
let result = Object.keys(people).reduce(function(r, name) {
return r[name] = people[name].age, r;
}, {});
document.write(['<pre>', JSON.stringify(result, 0, 3), '</pre>'].join(''));
One option if you're not super concerned about potential performance:
const ages = people.reduce(
(obj, name) => Object.assign(obj, {[name]: obj[name].age}), {});
or maybe
const ages = Object.entries(people).reduce(
(obj, [name, info]) => Object.assign(obj, {[name]: info.age}), {});
Or make an ES6 Map instead of using an Object:
const ages = new Map(Object.entries(people).map(
([name, info]) => [name, info.age])))
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