iterate object containing array javascript code example

Example 1: javascript object array iteration

let obj = {
  key1: "value1",
  key2: "value2",
  key3: "value3"
}

Object.keys(obj).forEach(key => {
  let value = obj[key];
  //use key and value here
});

Example 2: iterate through object array javascript

for (var key in array) {
    var obj = myArray[key];
    // ...
}

Example 3: iterate over array of objects javascript

// Count the number of each category

const people = [
    {name: 'John', group: 'A'}, 
    {name: 'Andrew', group: 'C'}, 
    {name: 'Peter', group: 'A'}, 
    {name: 'James', group: 'B'}, 
    {name: 'Hanna', group: 'A'}, 
    {name: 'Adam', group: 'B'}];

const groupInfo = people.reduce((groups, person) => {
    const {A = 0, B = 0, C = 0} = groups;
    if (person.group === 'A') {
        return {...groups, A: A + 1};
    } else if (person.group === 'B') {
        return {...groups, B: B + 1};
    } else {
        return {...groups, C: C + 1};
    }
}, {});

console.log(groupInfo); // {A: 3, C: 1, B: 2}