Best way to loop through object NodeJS

In the code section is a typical JSON object I am getting back

Was wondering what is the best way to loop in NodeJS, lint for some reason doesn’t like me using for (let item of myArray) it complains about 'ForOfStatement' is not allowed.

My current output comes out as the following:

Cont { id: 'Something1', mycontent: { foo: '1', bar: '1' } }
Cont { id: 'Something2', mycontent: { foo: '3', bar: '7' } }

so losing some of my values which I am assuming is due to me using Object.Entries as its key value pairs, whats the best way to loop round and retain these keys?

myObject = [{
     "id": "Something1",
     "mycontent": {
         "foo": "12",
         "foo": "1",
         "bar": "1"
     }
 },
     {
         "id": "Something2",
         "mycontent": {
             "foo": "3",
             "bar": "5",
             "bar": "7"
         }
     }
]

Object.entries(myObject).forEach((item) => {
 let myContent = item[1];
 console.log("Cont", myContent);
});

I expect the output of my object appear as:

Something 1: foo: 12, 1 : bar 1; Something2 : foo: 3, bar: 5, 7

3 answers

  • answered 2019-08-14 18:19 ANUPAM CHAUDHARY

    As far as I know, the key in any object gets stored as a string, and when you use the same key foo twice it would overwrite the first foo key value and the same with using bar twice, only the last bar key would be stored. You can manipulate the data being stored by converting foo and bar as an array to save multiple values.

  • answered 2019-08-14 18:19 TbWill4321

    You need to loop over it with a method from the Array.prototype: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

    myObject.forEach((item) => {
      const myContent = item[1];
      console.log("Cont", myContent);
    });
    

  • answered 2019-08-14 20:20 Saarett

    so losing some of my values which I am assuming is due to me using Object.Entries as its key value pairs

    You are not losing the values because of Object.Entries, you lose them the moment you try to define your "myObject" object. In a JS object, each key is unique. When you try to define this object:

    {
         "id": "Something2",
         "mycontent": {
             "foo": "3",
             "bar": "5",
             "bar": "7"
         }
     }
    

    you basically set the "bar" key only once, with the second assignment overriding the first, and this is the reason you get for an output:

    Cont { id: 'Something2', mycontent: { foo: '3', bar: '7' } }
    

    instead of

    Cont { id: 'Something2', mycontent: { foo: '3', bar: '5', bar: '7' } }
    

    As a small test, try to run this code:

    const myObj = {
        foo: '3',
        foo: '7'
    };
    
    console.log(myObj);
    

    You'll notice that the output is {foo: "7"}, as the new value is not appended to the previous value, nor the same key added.