Iterate Through Object Keys Javascript Code Example

Snippet 1

  var myObj = {foo: "bar", baz: "baz"};
Object.values(myObj).map((val) => {
console.log(val);
})
// "bar" "baz" 

Snippet 2

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

for (let [key, value] of Object.entries(object1)) {
  console.log(`${key}: ${value}`);
}

// expected output:
// "a: somestring"
// "b: 42"
// order is not guaranteed 

Snippet 3

  Object.keys(obj).forEach(e => console.log(`key=${e}  value=${obj[e]}`)); 

Snippet 4

  Object.keys(obj).forEach(function(key) {
  console.log(key, obj[key]);
}); 

Snippet 5

  var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3"
};

for (var key in p) {
    if (p.hasOwnProperty(key)) {
        console.log(key + " -> " + p[key]);
    }
} 

Snippet 6

  Object.entries(obj).forEach(
    ([key, value]) => console.log(key, value)
);

// Loop using forEach
arr.forEach((item, index) => {
    // TODO
})

// Loop using for...of
for (const item of arr) {
    await something()
}

// Clone new array (not changing the old one)
const arr = [1,2,3]
const newArray = arr.map(item => item * 2)
console.log(newArray)

// Filter array by condition
const arr = [1,2,3,1]
const newArray = arr.filter(item => {
    if (item === 1) { return item }
})
console.log(newArray)

// Join array
const arr1 = [1,2,3]
const arr2 = [4,5,6]
const arr3 = [...arr1, ...arr2]
console.log(arr3)

// Get a property of object
const { email, address } = user
console.log(email, address)

// Copy object/array
const obj = { name: 'my name' }
const clone = { ...obj }
console.log(obj === clone) 

Copyright © Code Fetcher 2020

 

 

Published

Leave a comment

Your email address will not be published. Required fields are marked *