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
}
CodePudding user response:
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 })))
CodePudding user response:
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);