Home > Mobile >  Sort a json with nested objects structure and return a format same as the structure of json
Sort a json with nested objects structure and return a format same as the structure of json

Time:12-18

My title for this ques. may not be appropriate but my problem is that I have a following type of json...

{
  "trees":{
     "name":"a",
     "age":"9",
     "height":"10",
     "location":"park"
  },
  "cars":{
     "name":"b",
     "age":"3",
     "height":"10",
     "location":"park"
  },
  "bikes":{
     "name":"c",
     "age":"110",
     "height":"10",
     "location":"park"
  }
}

Now I want to sort it according to age that is 3,9,110. And get hold of this sorted data in the same format that is

{
"cars":{
     "name":"b",
     "age":"3",
     "height":"10",
     "location":"park"
  },
  "trees":{
     "name":"a",
     "age":"9",
     "height":"10",
     "location":"park"
  },
  "bikes":{
     "name":"c",
     "age":"110",
     "height":"10",
     "location":"park"
  }
};

This format is essential for me because I pass it further to another react child component where I do several operations on it to send it further to further components.

I searched on the net and found ways to sort this array wherein firstly an array would be initialized and only the values of json would be pushed and not keys in that array and then the sorting would happen. That method works fine but the result array i get is of a different type then my original json which causes trouble is sending data further to components.

CodePudding user response:

var data = {
  "trees":{
     "name":"a",
     "age":9,
     "height":"10",
     "location":"park"
  },
  "cars":{
     "name":"b",
     "age":3,
     "height":"10",
     "location":"park"
  },
  "bikes":{
     "name":"c",
     "age":110,
     "height":"10",
     "location":"park"
  }
},
    sorted = {};

Object
    .keys(data).sort(function(a, b){
        return data[a].age - data[b].age;
    })
    .forEach(function(key) {
        sorted[key] = data[key];
    });

    console.log(sorted);

CodePudding user response:

Convert to an array of key-value pairs, then sort by the value's age property converted to a number, then convert back to an object from the entries array.

Object.fromEntries(
  Object.entries(data).sort(
    ([, objA], [,objB]) => Number(objA.age) - Number(objB.age)
  )
);

const data = {
  "trees": {
    "name": "a",
    "age": "9",
    "height": "10",
    "location": "park"
  },
  "cars": {
    "name": "b",
    "age": "3",
    "height": "10",
    "location": "park"
  },
  "bikes": {
    "name": "c",
    "age": "110",
    "height": "10",
    "location": "park"
  }
}

const sortedData = Object.fromEntries(
  Object.entries(data).sort(([, objA], [,objB]) => Number(objA.age) - Number(objB.age))
);

console.log(sortedData);

  • Related