user1400915
user1400915

Reputation: 1943

Iterating over json objects in array

I have an array called mainarray which has multiple json objects.

mainarray:Object
  >key1: Array[30]
  >key2: Array[20]

I want to do sorting on Array[30] and Array[20]. I am trying to do it like this:

mainarray.forEach((arrayinner)
{
  //sort
});

But I am getting error : as Cannot read property of undefined.

How can I iterate ? and also key names are dynamic ,I cant hardcode it and start iterating/

Upvotes: 2

Views: 479

Answers (4)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67217

You can do it by using $.each

$.each(mainarray, function(key,val){
  val.sort((a,b) => {return a > b ? 1 : a < b ? -1 : 0});
});

since the val is an array aka an object. Its reference will be shared inside of the callBack function. So affecting that array inside callBack will affect the original array.

DEMO

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337700

You could achieve this by looping over the properties of the object itself and sorting the arrays they contain, something like this:

for (var key in mainarray) {
    if (mainarray[key] === Array)
        mainarray[key].sort();
}

Working example

Note that by default sort() only uses basic alphanumeric sorting logic. If you need anything more complex you would need to implement that yourself.

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386816

You need the function keyword for a valid callback declaration.

mainarray.forEach(function (arrayinner)
//                ^^^^^^^^
{
  //sort
});

But the problem is deeper:

You need to get the keys and to iterate over them and take the propery value to apply a sort

Object.keys(mainarray).forEach(function (key) {
    mainarray[key].sort();
});

Upvotes: 3

gurvinder372
gurvinder372

Reputation: 68433

You can get the array of keys to iterate over

Object.keys ( mainarray ).forEach( function( arrayinner ){
  arrayinner.sort();
});

if the all the keys inside mainarray may not have Array value, then you can check before sorting

Object.keys ( mainarray ).forEach( function( arrayinner ){
  Array.isArray( arrayinner ) || arrayinner.sort();
});

Upvotes: 2

Related Questions