stackdave stackdave - 3 months ago 14
Javascript Question

javascript manipulating objects: map

I need to get a new object countriesFiltered , filtering just countries with population under a billion. I'm using in the map part: return { key : countries[key]}. I think is not correct, how i can build a new object ? i must use push or something like that?

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

Answer

Close! Just use Array.reduce instead of Array.map. Object property names can't be computed unless you are using ES2015. So you need to use reduce to construct a new object and then assign each property individually.

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

Comments