简体   繁体   中英

What is the best way to iterate multidimensional array in node.js/javascript?

I am trying to iterate multidimensional array in Node.js. I have array in JSON object like this :

{
    "operationalHours": [
        [
            {
                "opens": "11: 15AM",
                "closes": "11: 30AM"
            },
            {
                "opens": "11: 30AM",
                "closes": "11: 45AM"
            },
            {
                "opens": "11: 45AM",
                "closes": "12: 00PM"
            }
        ],
        [
            {
                "opens": "12: 15AM",
                "closes": "12: 30AM"
            },
            {
                "opens": "12: 30AM",
                "closes": "12: 45AM"
            },
            {
                "opens": "01: 00AM",
                "closes": "01: 15AM"
            }
        ]
    ]
}

Does anyone know the best way to iterate this in node.js?

The most "quicker" way to iterate an array in javascript is:

var i; 
for (i = myarray.length; i--;) {
  console.log(myarray[i]);
}

Iteration counter in a reverse order - from the biggest number to zero, usually increases the speed, because operation of comparison with 0 is a little more effective, than operation of comparison with array length or with any other number, different to 0.

To iterate object inside of each array element you can use for in cycle:

var i, j; 
for (i = myarray.length; i--;) {
  for (j in myarray[i]) {
      console.log(j, myarray[i][j]);  
  }
}

With lodash :

_.forEach(operationalHours, function(el, key) {

});

You can also find element:

var items = _.findWhere(operationalHours[0], {"opens": "11: 30AM"})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM