shairoo
shairoo

Reputation: 29

How to sort object of objects by nested key

i have an object of objects. i want to sort it on the basis of id.

here is my data

{
  1918: {
    id: "1544596802835",
    item_id: "1918",
    label: "Soft Touch  Salt Free Mint 500 ml (000001400045)",
    combo_items: false
  }

  6325: {
    id: "15445968134652",
    item_id: "6325",
    label: "Mirindas Orange Flover 300 ml (012000800160)",
    combo_items: false
  }

  6336: {
    id: "15445968106815",
    item_id: "6336",
    label: "Sting Energy 250ml (012000034220)",
    combo_items: false
  }

  6498: {
    id: "1544596806967",
    item_id: "6498",
    label: "Tido Candy (01)",
    combo_items: false
  }

  7461: {
    id: "15445968057103",
    item_id: "7461",
    label: "Skin Whitening Facial Kit (000051032012)",
    combo_items: false
  }
}

Upvotes: 0

Views: 2860

Answers (2)

Tran Bao
Tran Bao

Reputation: 1

You can try!

function sort(data) 
{
   return Object.keys(data)
   .sort().reduce((a, b) => {
   a[b] = data[b];
   return a; }, {});
}

const object = {9:"Name 9", 10:"Name 10", 2:"Name 2", 5:"Name 5", 3:"Name 3"};
var sortObject = sort(abject);

The result is

sortObject = {2: "Name 2", 3: "Name 3", 5: "Name 5", 9: "Name 9", 10: "Name 10"}

Upvotes: 0

Robby Cornelissen
Robby Cornelissen

Reputation: 97150

First of all, you shouldn't rely on property order in JavaScript objects (see this question for details), which means that you need to sort your objects into an array.

That can easily be done using Array.prototype.sort():

const sorted = Object.values(data).sort((a, b) => a.id - b.id);

Complete snippet:

const data = {
  1918: {
    id: "1544596802835",
    item_id: "1918",
    label: "Soft Touch  Salt Free Mint 500 ml (000001400045)",
    combo_items: false
  },
  6325: {
    id: "15445968134652",
    item_id: "6325",
    label: "Mirindas Orange Flover 300 ml (012000800160)",
    combo_items: false
  },
  6336: {
    id: "15445968106815",
    item_id: "6336",
    label: "Sting Energy 250ml (012000034220)",
    combo_items: false
  },
  6498: {
    id: "1544596806967",
    item_id: "6498",
    label: "Tido Candy (01)",
    combo_items: false
  },
  7461: {
    id: "15445968057103",
    item_id: "7461",
    label: "Skin Whitening Facial Kit (000051032012)",
    combo_items: false
  }
};

const sorted = Object.values(data).sort((a, b) => a.id - b.id);

console.log(sorted);

(I fixed the object literal as it was lacking commas between the properties)

Upvotes: 5

Related Questions