Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, }   
like image 750
AndrewMcLagan Avatar asked Feb 01 '26 02:02

AndrewMcLagan


2 Answers

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(''));
like image 123
Yuriy Yakym Avatar answered Feb 02 '26 15:02

Yuriy Yakym


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])))
like image 24
loganfsmyth Avatar answered Feb 02 '26 16:02

loganfsmyth