1

I need to loop through a REST response object, which has an object with objects. I am on ES5 javascript, and cannot change how the data is served.

This is for a ServiceNow script include, which is in javascript es5. for...of is not available. I have tried a for...in loop with the object, but I just get what each object is called(truncation). I need to loop through the "Objects" object in my code example code.

{
    "formatVersion": "v1.0",
    "someText": "Text",
    "someDate": "2019-11-08T18:51:37Z",
    "Objects": {
        "NestedObj1": {
            "prop1": "val1",
            "prop2": "val2",
            "prop3": "val3",
        },
        "NestedObj2": {
            "prop1": "val4",
            "prop2": "val5",
            "prop3": "val6",
        }
    }
}

I need to loop through a database insert. When the above JSON is converted to object, expecting something such as: for(var obj in someObjName.Objects) and then reference each property (the property names don't change) via obj.prop1.

Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153
Mark Kibbe
  • 11
  • 3
  • 3
    Remember that ES5 still has [Object.keys(...)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys), which yields the array of (enumerable) property names of any object your put in, which you can then `.forEach` and `.map` like any other array. – Mike 'Pomax' Kamermans Nov 10 '19 at 18:06
  • You wouldn't use `for … of` anyway even if ES6 was available, since there are no iterable arrays in your object. – Bergi Nov 10 '19 at 18:09
  • You need to use `someObjName.Objects[obj].prop1`, as `obj` is the *key* in the `for (var obj in …)` loop – Bergi Nov 10 '19 at 18:10

0 Answers0