1let obj = {
2 key1: "value1",
3 key2: "value2",
4 key3: "value3",
5 key4: "value4",
6}
7Object.entries(obj).forEach(([key, value]) => {
8 console.log(key, value);
9});
1Object.entries(obj).forEach(([key, value]) => {
2 console.log(key, value);
3});
1for (const [key, value] of Object.entries(object1)) {
2 console.log(`${key}: ${value}`);
3}
4
1// Object Entries returns object as Array of [key,value] Array
2const object1 = {
3 a: 'somestring',
4 b: 42
5}
6Object.entries(object1) // Array(2) [["a", "something"], ["b", 42]]
7 .forEach(([key, value]) => console.log(`${key}: ${value}`))
8// "a: somestring"
9// "b: 42"
1// Access all properties and values in a JS object:
2let valuesArray = Object.entries(MyObject);
3
4 for (let value of valuesArray) {
5 document.write(value + "<br>"); // value is the property,value pair
6 }
7/* Result: propName,value
8 propName,value
9 ...
10
11For clarity: */
12let person = {
13 name: "Piet",
14 age: 42
15};
16
17Object.keys(person) // = ["name", "age"]
18Object.values(person) // = ["Piet", 42]
19Object.entries(person) // = [ ["name","Piet"], ["age",42] ]
20
1var obj = { foo: 'bar', baz: 42 };
2console.log(Object.entries(obj)); // [ ['foo', 'bar'], ['baz', 42] ]
3
4// objeto array-like
5var obj = { 0: 'a', 1: 'b', 2: 'c' };
6console.log(Object.entries(obj)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]
7
8Object.entries(obj).forEach(([key, value]) => {
9 console.log(key + ' ' + value); // "a 5", "b 7", "c 9"
10});
11