Object.keys, values, entries

Object.keys, values, entries

  • Object.keys(obj) – returns an array of keys.

  • Object.values(obj) – returns an array of values.

  • Object.entries(obj) – returns an array of [key, value] pairs.

Map

Object

Call syntax

map.keys()

Object.keys(obj), but not obj.keys()

Returns

iterable

“real” Array

let user = {
  name: "John",
  age: 30
};

Object.keys(user) = ["name", "age"]
Object.values(user) = ["John", 30]
Object.entries(user) = [ ["name","John"], ["age",30] ]

// loop over values
for (let value of Object.values(user)) {
  alert(value); // John, then 30
}

Object.fromEntries to transform objects

把 object 變成 map 用 new Map(Object.entries(obj))。把 map 變成 object 用 Object.fromEntries([[key1, value1], [key2, value2]])

let prices = Object.fromEntries([
  ['banana', 1],
  ['orange', 2],
  ['meat', 4]
]);

// now prices = { banana: 1, orange: 2, meat: 4 }

alert(prices.orange); // 2

// loop through array
let prices = {
  banana: 1,
  orange: 2,
  meat: 4,
};
let doublePrices = {};
for(let [product, price] of Object.entries(prices)) {
  doublePrices[product] = price * 2;
}
alert(doublePrices.meat); // 8

// convert to object
let prices = {
  banana: 1,
  orange: 2,
  meat: 4,
};
let doublePrices = Object.fromEntries(
  // convert to array, map, and then fromEntries gives back the object
  Object.entries(prices).map(([key, value]) => [key, value * 2])
);
alert(doublePrices.meat); // 8

// convert map to object
let map = new Map();
map.set('banana', 1);
map.set('orange', 2);
map.set('meat', 4);
let obj = Object.fromEntries(map);
// now obj = { banana: 1, orange: 2, meat: 4 }
alert(obj.orange); // 2

Last updated