0

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
}

2 Answers 2

1

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 })))

Sign up to request clarification or add additional context in comments.

1 Comment

My pleasure, I just edit my answer, I saw that you don't need to pass by the Object.fromEntries(Object.entries()) part
1

You can simply iterate the key/values of obj2 and place them into obj1 and it will order itself.

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


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

for (const [key, value] of Object.entries(obj2)) {
    obj1[key] = value;
}
console.log(obj1);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.