使用es6 javascript可以迭代一个对象并返回一个新对象。例如:
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, }
答案 0 :(得分:6)
您可以使用数组原型的reduce
方法。它也适用于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(''));
答案 1 :(得分:1)
如果您不是非常关注潜在的表现,可以采用一种方法:
const ages = people.reduce(
(obj, name) => Object.assign(obj, {[name]: obj[name].age}), {});
或者
const ages = Object.entries(people).reduce(
(obj, [name, info]) => Object.assign(obj, {[name]: info.age}), {});
或者制作ES6 Map
而不是使用Object
:
const ages = new Map(Object.entries(people).map(
([name, info]) => [name, info.age])))
答案 2 :(得分:0)
这是一种方法,我希望我能相信这一点,它来自Axel Rauschmayer的博客,他还有其他几个惊人的博客文章:http://www.2ality.com/2015/02/es6-iteration.html
function objectEntries(obj) {
let index = 0;
let propKeys = Reflect.ownKeys(obj);
return {
[Symbol.iterator]() {
return this;
},
next() {
if (index < propKeys.length) {
let key = propKeys[index];
index++;
return { value: [key, obj[key]] };
} else {
return { done: true };
}
}
};
}
let obj = { first: 'Jane', last: 'Doe' };
for (let [key,value] of objectEntries(obj)) {
console.log(`${key}: ${value}`);
}
如果您使用生成器,这会更容易:http://www.2ality.com/2015/03/es6-generators.html
答案 3 :(得分:0)
不幸的是,对于ES6中的对象,它不等于Array.map
。
也许你可以制作一个帮助函数来模仿这个。它将遍历您的对象,使用该键的值调用每个键的回调,并将该值替换为回调返回的任何值。类似的东西:
const objectMap = (obj, cb) =>
Object.keys(obj).reduce((ppl, k) =>
Object.assign(ppl, {
[k]: cb(obj[k])
}), {}
);
然后使用它:
const newPeople = objectMap(people, val => val.age);
console.log(newPeople); // Object {Sally: 22, John: 64, Sam: 12}
运行示例:
const people = {
'Sally': {
age: 22,
sex: 'female',
},
'John': {
age: 64,
sex: 'male',
},
'Sam': {
age: 12,
sex: 'female',
},
};
const objectMap = (obj, cb) =>
Object
.keys(obj)
.reduce(
(ppl, k) =>
Object.assign(ppl, {
[k]: cb(obj[k])
}), {}
);
const newPeople = objectMap(people, val => val.age);
console.log('---- People ----');
console.dir(people);
console.log('---- New People ---- ');
console.dir(newPeople);
&#13;
答案 4 :(得分:-1)
也许你可以使用for...of
?
const people = { 'Sally': { age: 22, sex: 'female', }, 'John': { age: 64, sex: 'male', }, 'Sam': { age: 12, sex: 'female', },
};
const ages = {};
for(let index of people) {
ages[key] = people[key].age;
}
console.log(ages); // { 'Sally': 22, 'John': 64, 'Sam': 12, }