Object.keys, values, entries
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
}
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