javascript code to combine two JSON objects with numeric string keys and sort them in ascending order

Is there a way to combine two JSON objects with numerical string keys and arrange them in ascending order?

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


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

   // Desired output:

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

Answer №1

Revise

It appears that the keys are already sorted by the spread, so you simply need to use it.

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


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

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

Prior response

The Object.entries method orders the keys, allowing you to then utilize Object.fromEntries in order to have your object sorted correctly.

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


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

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

Answer №2

To rearrange the order of key/values in obj1, you can iterate through the key/values of obj2 and assign them to obj1.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Trouble arises as Amchart and Ajax encounter data that is not in the

I am trying to utilize AmChart and retrieve data for charts from PHP. Below is my PHP file: $colors = Array("#FF0F00","#FF6600","#FF9E01","#FCD202","#F8FF01","#B0DE09","#04D215","#0D8ECF","#0D52D1","#2A0CD0","#8A0CCF","#CD0D74","#754DEB","#DD ...

"Uncovering the mystery of the missing element in Jquery's open

I have developed a click-to-show feature that opens and closes a div from left to right. You can view the demo here on jsfiddle.net In the demo, you will find a green-colored div. Upon clicking this div, another div opens from left to right. An interesti ...

Parsing JSON data into different data types in C#

I am looking for a way to transfer various types of data from JavaScript to C#. Specifically, I want to send a JSON object from the JavaScript side using an AJAX call. Here is an example: AnObject = new Object; AnObject.value = anyValue; $.ajax({ typ ...

What is causing the initial $.ajax call to fail when sending a data object?

I'm facing an issue with the first $.ajax() call. I need to include URL parameters in the ajax data property. To see this problem in action, check out this fiddle: http://jsfiddle.net/f9e5Y/ Below is the JavaScript code: var urlParameters = { pag ...

How to transform a JSON string with escape characters into valid JSON using Ans

I'm struggling to convert an Ansible output into JSON without escaped strings. The output looks like this: { "msg": [ "{", "\t\"inprog\" : [", "\t\t{", "\t\t\t\"desc&bso ...

Guide to organizing a JavaScript object using a parent-child tree structure

Below is the JavaScript Object structure that I currently have: [ [ null, "A" ], [ "A", "B" ], [ "A", "C" ], [ null, "D" ], [ "D", "E" ], [ "D ...

What is the significance of $() in jQuery?

I understand that $() is a selector, but I find it puzzling as to what it actually selects since there is nothing inside the parentheses. Is this a common practice or frowned upon in coding conventions? An example of where I have seen it used is when maki ...

Using the ref callback to access getBoundingClientRect values in React Components

I'm having some trouble extracting data using the getBoundingClientRect() method from a set of animated div elements. The issue I'm facing is that the refCallback function is returning empty DOMRect objects. If you're interested, feel free t ...

When a controller includes Axios or Node HTTPS requests, Express fails to send a response

Currently, I am in the process of integrating with an external webhook through Wix.com's API. However, I have encountered a problem where the presence of an Axios request or a raw Node HTTP/HTTPS request is causing issues with sending the response. B ...

Loading content with AJAX without having to refresh the page

I've been working on implementing a way to load content onto a page without needing to refresh it. While I was able to achieve this, I encountered a problem where the images and CSS files weren't loading properly. Below is the code I used: < ...

Having trouble with React MaterialUI <ListItemSecondaryAction> getting stuck while dragging within a react-beautiful-dnd Draggable?

I am currently utilizing react-beautiful-dnd to create draggable list items with the help of Material UI ListItems. Each of my ListItems consists of a ListItemText and a ListItemSecondaryAction which acts as a target for triggering a context menu (enclosi ...

"Simultaneously creating a Firebase user account and populating the database with user

My goal is to store new user information in my database using their unique user UID when they sign up through Firebase. Currently, my code is functioning properly, however, I am facing an issue where the name (which should be the created user UID) appears ...

Navigating through directory paths in JavaScript can be a daunting task for many

In my app.js file, I've included the following code: app.use(multer({dest:'./uploads'})) What does './uploads' refer to here? It is located in the same directory as app.js. In what way does it differ from simply using uploads? I ...

Transforming a few lines of PHP header code to Classic ASP

I am encountering an issue with two files that I have: A locally hosted project coded in Ionic/AngularJS that is attempting to retrieve JSON data from an ASP file. An external ASP File which generates JSON data based on database values from a query. Eve ...

Struggling to incorporate blocks into Jade for Express. Encountering errors like "Max Stack Size Exceeded" and issues with setHeader

I am currently using Express along with a simple express-generator server that I created. My first task was to focus on creating the view layout and extending the index page, but unfortunately, I have encountered some challenges. Throughout my process, I& ...

The debate between using multiple modals or a single overwritable modal remains a

I am in the process of creating a webpage that will contain multiple elements. For example, it could be a gallery of books where clicking on a thumbnail opens a modal with the book's image, a link to the publisher (or personal book page), and a descri ...

"Kindly complete all mandatory fields" - The undisclosed field is preventing me from submitting

I am facing an issue with my WordPress page that has Buddyboss installed along with Elementor pro as the Pagebuilder. The Buddyboss plugin provides Facebook-like functions on the website. While it is easy to comment on posts within the Buddy Boss system, I ...

Convert the data into a format that is compatible with JavaScript

Having trouble extracting a value from json and placing it into my controller. I want to assign the membership value of 8 to $scope.value = data.membership; Service call in JS: .service('getMembership', function ($http, SERVER_URL) { r ...

When a user clicks a button, modify a section of the URL and navigate to

I've been searching everywhere for a solution to this issue, but I just can't seem to find it. I'm hoping someone here can help me out. In a bilingual store, I need a way to redirect users to the same product on a different domain when they ...

Omitting "a" elements with a designated ancestor from a jQuery scroll operation

I successfully added smooth scrolling to my webpage using the provided script. However, I also have a section with tabs where I do not want the smooth scrolling effect. Here is my jQuery code: $('a[href*="#"]') // Remove links that don&apos ...