javascript - Iterating objects in es6 and returning new object -
using es6 javascript possible iterate on object , return new object. 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. 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
Post a Comment