francky
francky

Reputation: 177

Loop through all keys of multiple objects

Hello guys i have a same problem i wan't to add a loop objects inside array that's my array

const arrayDatas = [
  0: {id:234, name: eric},{id:235, name: thomas},{id:236, name: louvin},
  1: {id:230, name: jason},{id:233, name: lois},{id:238, name: serge},{id:237, name: natasha},{id:236, name: berthe}
]

Desired output loop to add all id arrayDatas of each keys

0: [234, 235, 236],
1: [230, 233, 238, 237, 236]

tha't is my attemp

products() {
      const details = Object.entries(arrayDatas);
      let detailsProducts = [];
      details.forEach(([key, val]) => {
        detailsProducts.push(val.id);
      });
      return detailsProducts;
    }

is don't work please help

Upvotes: 0

Views: 479

Answers (1)

tam.teixeira
tam.teixeira

Reputation: 863

arrayDatas.map(details => details.map(d => d.id))

Working example:

const arrayDatas = [
  [{id:234, name: 'eric'},{id:235, name: 'thomas'},{id:236, name: 'louvin'}],
  [{id:230, name: 'jason'},{id:233, name: 'lois'},{id:238, name: 'serge'},{id:237, name: 'natasha'},{id:236, name: 'berthe'}]
];

console.log(arrayDatas.map(details => details.map(d => d.id)))

Or you can also do it with nested for loop:

    const arrayDatas = [
      [{id:234, name: 'eric'},{id:235, name: 'thomas'},{id:236, name: 'louvin'}],
      [{id:230, name: 'jason'},{id:233, name: 'lois'},{id:238, name: 'serge'},{id:237, name: 'natasha'},{id:236, name: 'berthe'}]
    ];

    let result = [];
    for(let details of arrayDatas) {
        let currentDetails = []
        for(let d of details) {
            currentDetails.push(d.id);
        }
        result.push(currentDetails);
    }
    console.log(result);

Upvotes: 2

Related Questions