AndrewMcLagan AndrewMcLagan - 7 months ago 18
Javascript Question

Iterating objects in es6 and returning new object

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, }

Answer

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(''));

Comments