CityRay/Blog

[JS] Manipulating(iterate) objects with Object.keys()

CityRay opened this issue · 0 comments

Object.keys()

將 Object 中的 Key 轉換成 Array,然後再運用 Array (forEach, map) 進行 loop.

Sample 1

// Sample 1
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj));

for (let key of Object.keys(obj)) {  
  let objName = obj[key];
  // ... do something with obj
  console.log(objName);
}

Sample 2

// Sample 2
var nameObj = {first: "Zaphod", last: "Beeblebrox"};
Object.keys(nameObj).forEach(function(key) {
    console.log(key + ': ' + nameObj[key]);
});

Sample 3

// Sample 3
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 countries[key];
});
console.log(countriesFiltered);

refer