我需要得到一个新对象 countriesFiltered ,只过滤人口在 10 亿以下的国家。我在 map 部分使用:return { key : countries[key]}。我认为不正确,我如何构建一个新对象?我必须使用推送或类似的东西吗?
var countries = {
China: 1371980000,
India: 1276860000,
'United States': 321786000,
Indonesia: 255461700,
Brazil: 204873000,
Pakistan: 190860000
};
var countriesFiltered = Object.keys(countries).filter(function(key) {
return countries[key] <= 1000000000;
}).map(function(key) {
return { key : countries[key]};
});
console.log(countriesFiltered);
最佳答案
关闭!只需使用 Array.reduce
而不是 Array.map
。对象属性名称不能是 computed除非你使用的是 ES2015。因此,您需要使用 reduce
构造一个新对象,然后单独分配每个属性。
var countries = {
China: 1371980000,
India: 1276860000,
'United States': 321786000,
Indonesia: 255461700,
Brazil: 204873000,
Pakistan: 190860000
};
var countriesFiltered = Object.keys(countries).filter(function(key) {
return countries[key] <= 1000000000;
}).reduce(function(obj, key) {
// Assign key/val to new object
obj[key] = countries[key];
return obj;
}, {});
document.write('<pre>' + JSON.stringify(countriesFiltered, null, 2) + '</pre>');
编辑:使用 ES2015 计算名称属性将类似于以下内容。 请注意,这仅适用于受支持的浏览器。
var countries = {
China: 1371980000,
India: 1276860000,
'United States': 321786000,
Indonesia: 255461700,
Brazil: 204873000,
Pakistan: 190860000
};
var countriesFiltered = Object.keys(countries).filter(function(key) {
return countries[key] <= 1000000000;
}).reduce(function(obj, key) {
// Create object with computed property name
// and assign to obj
return Object.assign(obj, {
[key]: countries[key]
});
}, {});
document.write('<pre>' + JSON.stringify(countriesFiltered, null, 2) + '</pre>');
好处:为了好玩,您可以使用 replacer
函数来利用 JSON.stringify
的强大功能过滤对象。虽然它确实表明有很多不同的方法可以解决这个问题,但我不推荐这种方法。
var countries = {
China: 1371980000,
India: 1276860000,
'United States': 321786000,
Indonesia: 255461700,
Brazil: 204873000,
Pakistan: 190860000
};
var countriesFiltered = JSON.parse(JSON.stringify(countries, filterCountries));
function filterCountries(key, val) {
if (val > 1000000000) {
return undefined;
}
return val;
}
document.write('<pre>' + JSON.stringify(countriesFiltered, null, 2) + '</pre>');
关于javascript 操作对象 : map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38909671/