0

I want to know how to short object based on array inside each object, here is my array object:

var cars = {
  'Ferrari': {
    'Ascari': {color: 'Yellow', year: 2005},
    'Enzo': {color: 'Red', year: 2003}
  }
};

I want to sort them based on car year, so I want output like this:

var cars = {
  'Ferrari': {
    'Enzo': {color: 'Red', year: 2003}
    'Ascari': {color: 'Yellow', year: 2005},
  }
};

Please let me know how to do that, really appreciate for any help :)

Fil
  • 8,225
  • 14
  • 59
  • 85
Luxor
  • 45
  • 1
  • 9

1 Answers1

1

You can't sort the properties of the object, because properties don't have an order. And also there is no use of that. Iterating over the properties will not give you them in which order you have set them.

It will be better to have cars as array and use sort to sort them.

var cars = {
    'Ferrari': [
        { name: 'Ascari', color: 'Yellow', year: 2005 },
        { name: 'Enzo', color: 'Red', year: 2003 }
    ]
};

cars['Ferrari'].sort((a,b) => a.year - b.year);
console.log(cars);
Striped
  • 2,544
  • 3
  • 25
  • 31
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112