Home > Mobile >  Type script object iteration
Type script object iteration

Time:09-22

Am using foreach for iterate to first level.This is my Json object

{
    "Parent1": [
        {
            "Data1": [
                "Item1",
                "Item2"
            ]
        }
    ],
    "Parent2": [
        {
            "Data2": [
                "Item3",
                "Item4"
            ]
        }
    ]
}

.ts file

Object.keys(parent).forEach((key: any) => {
      let value = parent[key];
      tmpData = parent[key];
      console.log(tmpData[0]);

    });

above code will iterate the first level.How can i get below value?

 "Data1": ["Item1",
           "Item2"
          ]

Do i need to use nested fearch?

Do we have any other solutions?

Thanks in advance.

Expecting a better solution.

CodePudding user response:

Yes. You have to use the nested forEach in my opinion. But it would be better to iterate like following:

Object.values(parent).forEach((level1Item: any) => {
    let level1Children = Object.values(level1Item[0]);
});

CodePudding user response:

Let me flex a little here with generator functions :

const data = {
  Parent1: [{ Data1: ['Item1', 'Item2'] }],
  Parent2: [{ Data2: ['Item3', 'Item4'] }],
};

data[Symbol.iterator] = function*() {
  for (const parent of Object.values(this))
    for (const child of parent)
      for (const data of Object.values(child))
        for (const item of data)
          yield item;
  return;
}

for (const item of data) console.log(item);

Amazing isn't it ?

Generator functions can be used to loop over objects when declared correctly. Give it a try !

Documentation

A second solution, which is easier to understand, to do the same :

const data = {
  Parent1: [{ Data1: ['Item1', 'Item2'] }],
  Parent2: [{ Data2: ['Item3', 'Item4'] }],
};

for (const parent in data)
  for (const child of data[parent])
    for (const key in child)
      for (const item of child[key])
        console.log(item);

  • Related