[Solved] Access array of object elements in order from object field? [duplicate]


Hello you have to sort your object. Just use .sort of the array for that.

Here is a sample:

var obj = {
    "foo": "bar",
    "baz": [
        {
            "order": 2,
            "fruit": "banana"
        },
        {
            "order": 1,
            "fruit": "apple"
        },
        {
            "order": 3,
            "fruit": "peach"
        },
    ]
}

// get property
var arr = obj["baz"];

// may copy array
var counter = arr.length;
var arrCopy = new Array(counter);
while(counter--) {
    arrCopy[counter] = arr[counter];
}

// sort 
arrCopy.sort(function(a, b) { return a.order - b.order});

// iterate it
arrCopy.forEach(function(v) {
  console.log(v.fruit);
})

5

solved Access array of object elements in order from object field? [duplicate]