Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to merge two json objects if keys are in numeric string and arrange in ascending order

How to merge two json objects if their keys are in numering string and arrange in ascending order

let obj1 = {
'10' : "ten"
'2' : "two",
"30": "thirty
}


let obj2 = {
'4' : "four",
'5' : "five",
"1": "one"
}

   // output i want :

let res = {
"1": "one",
'2' : "two",
'4' : "four",
'5' : "five",
'10' : "ten"
"30": "thirty
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Edit

It seems the spread already sort the keys so you just need it

let obj1 = {
  '10': "ten",
  '2': "two",
  "30": "thirty"
}


let obj2 = {
  '4': "four",
  '5': "five",
  "1": "one"
}

console.log({ ...obj1, ...obj2 })

Previous answer

Object.entries order the keys, you can then run Object.fromEntries and you have your object sorted

let obj1 = {
  '10': "ten",
  '2': "two",
  "30": "thirty"
}


let obj2 = {
  '4': "four",
  '5': "five",
  "1": "one"
}

console.log(Object.fromEntries(Object.entries({ ...obj1, ...obj2 })))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading