Handle 2 json files with Javascript

Asked

Viewed 39 times

0

I have 2 json with the following structure and would like to put them in the same order through id. It is only an example the 2 json originally has more than 1000 lines but follow this same structure.

{
   "data":{
      "json_1":[
         {
            "id":123,
            "name":"Lucas"
         },
         {
            "id":145,
            "name":"Estevam"
         }
      ]
   }
}
{
   "data":{
      "json_2":[
         {
            "id":145,
            "name":"Estevam"
         },
         {
            "id":123,
            "name":"Lucas"
         }
      ]
   }
}

How json 2 should look:

{
   "data":{
      "json_2":[
         {
            "id":123,
            "name":"Lucas"
         },
         {
            "id":145,
            "name":"Estevam"
         }
      ]
   }
}
  • You want to organize by ID order or just want to organize this specific case same?

  • put an example of the expected result because it is not clear

  • @Lucasmódolo By ID, as I said in my current issue these 2 json are just one example, the original has + 1000 lines but follow the same structure. I hope with an example I understand better.

  • @Ricardopontual Pus.

  • @Lucasestevam Responded.

1 answer

2


You can use the method Sort

Example:

let json = {
   "data":{
      "json_2":[
         {
            "id":145,
            "name":"Estevam"
         },
         {
            "id":123,
            "name":"Lucas"
         }
      ]
   }
}

json.data.json_2.sort((a, b) => a.id - b.id)

console.log(json)

Sort is a method that organizes arrays according to a comparison method. In the case of the above code, the comparison method is this function within the method.

Sort checks the current Index and the Index later, they being the a and the b. The function takes the value a and b and returns the difference between them. If it is a positive value, it means that b is greater than a, then b is moved to an index prior to a.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.