object.keys and object.values code example

Example 1: Return the Objects Keys and Values

const keysAndValues = (obj) => [Object.keys(obj), Object.values(obj)];

keysAndValues({a: 1, b: 2, c: 3}); 
//➞ [["a", "b", "c"], [1, 2, 3]]

keysAndValues({a: "Dell", b: "Microsoft", c: "Google"}));
//➞ [["a", "b", "c"], ["Dell", "Microsoft", "Google"]]

keysAndValues({key1: true, key2: false, key3: undefined});
// ➞ [["key1", "key2", "key3"], [true, false, undefined]]

Example 2: javascript object get value by key

const person = {
  name: 'Bob',
  age: 47
}

Object.keys(person).forEach((key) => {
  console.log(person[key]); // 'Bob', 47
});

Example 3: javascript access property values list of objects

// Access all properties and values in a JS object:
let valuesArray = Object.entries(MyObject);
  
   for (let value of valuesArray) { 
       document.write(value + "<br>"); // value is the property,value pair
   } 
/* Result: propName,value
           propName,value
 		   ...

For clarity: */
let person = {
  name: "Piet",
  age: 42
};

Object.keys(person) // = ["name", "age"]
Object.values(person) // = ["Piet", 42]
Object.entries(person) // = [ ["name","Piet"], ["age",42] ]

Example 4: object.keys

const object1 = {
  a: 'somestring',
  b: 42,
  c: false
};

console.log(Object.keys(object1));
// expected output: Array ["a", "b", "c"]