0

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.

1
  • Could you clarify what you're trying to do exactly? The value you want to get is not valid JavaScript (it looks like an object literal with no surrounding curly braces) and you can get it by just writing parent.Parent1. Are you trying to walk through properties of object of arbitrary depth like this or something? Please consider providing a minimal reproducible example that demonstrates your issue when pasted, as-is, into a standalone IDE. I'm happy to help but I am not sure what you are really trying to do. Commented Sep 23, 2022 at 19:37

2 Answers 2

1

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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]);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.