1

I have a test nested JSON string.

const testString = `{
  "object1": {
    "5": [
      {
        "id": "A2OKPZ5S9F78PD",
        "rate": "2",
        "item": "item",
        "status": "status"
      }
    ]
  },
  "type": "LIVE_EVENT"
}`;

const model = JSON.parse(testString);
Object.values(model.object1).forEach((obj) =>
  obj.foreach((innerObj) => console.log(innerObj))
);

As you can see above I am trying to parse this as JSON and iterate over. The problem which I am facing during JSON.parse the inner object assumes the type undefined and foreach can not be applied on it. Can some one please help ?

9
  • (obj || []).forEach Commented May 5, 2020 at 4:57
  • Tried changing to this Object.values(model.object1).forEach(obj => (obj || []).foreach(innerObj => console.log(innerObj))); Still did not work Commented May 5, 2020 at 4:58
  • it's forEach not foreach, still the same? Commented May 5, 2020 at 5:00
  • Still does now work. Tried this. Object.values(model.object1).forEach(obj => (obj || []).forEach(innerObj => console.log(innerObj))); Commented May 5, 2020 at 5:01
  • model.object1 is indeed an object, so you need to iterate its properties stackoverflow.com/questions/684672/… Commented May 5, 2020 at 5:01

1 Answer 1

1

Your JSON is was invalid (before an edit) due to an extra comma after the status key/value pair and forEach() has an uppercase E. Also, as discussed in the comments below it seems you need to cast the inner obj to be of a type that understands forEach():

const testString = `{"object1":{"5":[{"id":"A2OKPZ5S9F78PD","rate":"2","item":"item","status":"status"}]},"type":"LIVE_EVENT"}`;
const model = JSON.parse(testString);
Object.values(model.object1).forEach((obj) =>
  (obj as any).forEach((innerObj) => console.log(innerObj))
);

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

10 Comments

I am running the same code you pasted here on typescript. It says forEach can not be applied over undefined.
Check if your JSON.parse(testString) is actually parsing the json, i.e., log the model variable.
@DarkShadows Can you share SS of that?
Make sure that when you run the code above, you're actually having exactly the same testString as I do, because when I run locally it works.
@LuísRamalho Yes (obj as any) worked. Thank you very much. Can you update your answer so that I can mark as accepted.
|

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.