Ways to insert an array into an array of objects

Here is the output received from the API:

[
  {
    "order": 0,
    "section_menu_id": 3
  },
  {
    "order": 1,
    "section_menu_id": 1
  }
]

This represents the initial data:

{
  "ordering_data": [
    {
      "order": null,
      "section_menu_id": null
    }
  ]
}

Desired output should look like this:

{
  "ordering_data": [
    {
      "order": 0,
      "section_menu_id": 3
    },
    {
      "order": 1,
      "section_menu_id": 1
    }
  ]
}

Could someone guide me on achieving the expected result? Thank you in advance.

Answer №1

let resultFromAPI = [
  {
    "order": 0,
    "section_menu_id": 3
  },
  {
    "order": 1,
    "section_menu_id": 1
  },
]

const startingInfo = {
  "ordering_data": [
    {
      "order": null,
      "section_menu_id": null
    }
  ]
}

startingInfo.ordering_data = resultFromAPI;

Answer №2

Take a look at the code snippet provided below. To append data to an array without overwriting the variable value, utilize the JavaScript array push method as demonstrated in the snippet: (otherwise it will simply result in a new assignment to the variable)

const res = [
  {
    "order": 0,
    "section_menu_id": 3
  },
  {
    "order": 1,
    "section_menu_id": 1
  }
];

const objContainer = {
  "ordering_data": [
    {
      "order": null,
      "section_menu_id": null
    }
  ]
};

//  objContainer["ordering_data"].splice(0,1); // (uncomment to get the desired result)
res.forEach(obj => objContainer.ordering_data.push(obj));
console.log(objContainer)

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

Sending property value to computed properties within a component

Is it considered a best practice to utilize a prop value within a computed property function of a component? If so, how can I construct the return statement using this prop? Carousel.vue props: [ 'source', ], computed: { items () { re ...

Convert a 6x3 DataFrame into a unique 9x2 array by selecting specific elements from the DataFrame to populate the array

from pandas import DataFrame import numpy as np Data={'First':[1,2,3,4,5,5],'Second':[6,7,8,9,10,4],'Third':[0,1,0,1,0,100]} df=DataFrame(Data,columns=['First','Second','Third']) In this segment ...

Issue with updating required Node.js/Express modules using Chokidar?

After browsing through numerous questions and answers regarding chokidar, I am still struggling with an issue. It would be greatly appreciated if someone could help debug my particular code snippet. The Express node app I am working on is running at local ...

Exporting keys of objects one by one

I am trying to mock the `fs` module in vitest using [memfs](https://github.com/streamich/memfs). To do this, I have created a mock file located at `./__mocks__/fs.ts` where I have set up the mocked volume and fs. However, I am facing an issue with the moc ...

When using ngClick with a parameter, the parameter is not being successfully passed

My table resembles a tree structure with two ng-repeats. <table> <tr ng-repeat-start="am in anArray"> <td><button ng-click="TheFunction(am)"></button></td> </tr> <tr ng-repeat-start="em in anotherArray"> < ...

Changing a number from 0 to 1 in a field using AngularJS (HTML5)

It's strange behavior. I am using an input field with the type set to number. When I enter 1230, the model value remains as 1230. However, when I type 01, it becomes 1. Even though I can see 01 in the input value, there seems to be something relate ...

The information was not displayed in the message exchange

I'm currently working on a project involving a google chrome extension where the content.js script sends a message to popup.js. I'm also attempting to take some text from content.js and display it in popup.js. Here is my entire code: Here's ...

Nuxt.js is throwing a TypeError because it is unable to access the 'minify' property since it is undefined

When I try to generate a Nuxt app using "npm run generate" or "npm run build", I encounter an issue where it throws a TypeError: Cannot read property 'minify' of undefined. Does anyone know how to solve this? TypeError: Cannot read property &apo ...

Choose a particular optgroup simultaneously using custom JavaScript

Check out this Fiddle for an example I am facing a situation where I have two different types of option groups with options. My challenge is to ensure validation between these two groups. How can I achieve this? Situation 1 If I select something from g ...

Retrieving the ID value and activating a click function for each link sharing a common class using jQuery

I'm facing a challenge in enabling the click function for every link with the same class name and unique id. Currently, the click function is only working on the first link, but there could be any number of links - 1, 2, 3, or more... To tackle this ...

Utilizing Bootstrap Modal functionality in a Django web application to enhance user experience

I am currently facing a minor issue in my Django application. I am attempting to utilize a modal from Bootstrap 4 along with AJAX to create a new object. Below you can view the code I used. However, when the user clicks the button, instead of seeing the mo ...

How can I load a function from the HTML file that is being loaded using .load() in jQuery?

Within my main window main.html, there is a div button that, when clicked, loads another html file into a large div. This is achieved using the .load() function: $('#mainpanel').load("search.htm"); The "search.htm" file contains a function cal ...

Unable to retrieve information from the Dark Sky API

Hourly weather information from the Dark Sky API is what I seek every hour, but the code comes to a halt at the line where it checks if let data = hourly["data"] as? [String : AnyObject] (confirmed by adding print statements after each line). I am unsure o ...

Using jQuery to transfer data via POST method

I'm currently working on integrating a third-party tool into our website. The tool requires the use of a form with the post method to send data to their site. Is there a way for me to replicate this action without relying on the form tag? I am not ver ...

Issue with Slim framework's REST API on 000webhost(free web hosting server)

After creating an API using the SLIM framework and hosting it on 000webhost.com, I encountered a problem when trying to access the API using a REST client. The server kept redirecting me to , even though the response code was 200 OK. I spent the entire d ...

Searching for data in MongoDB with multiple conditions using the Mongoose find

When I attempt to verify a verification code during user registration, the query has multiple conditions. If a document is returned, then the verification code is considered verified; otherwise, it is not. The issue with the following snippet is that it ...

Transform the value of Material-UI DatePicker to seconds

I am trying to figure out how to convert the value from a React Material-Ui datepicker, which currently looks like this: 2021-05-26T01:30, into seconds. Any suggestions on how I can achieve this? PS: My goal is to create a schedule SMS module. Therefore, ...

Experiencing difficulties with JWT implementation and seeking to transmit the JWT token to additional APIs

I am currently working on implementing JWT authentication in node js/express js: Below is the sample code I have written for this purpose: const jwt = require('jsonwebtoken'); const secretKey = crypto.randomBytes(64).toString('hex'); c ...

Dimension of the element that has been positioned absolutely

One of my challenges involves working with an absolutely positioned div element (.tooltip) containing another div (.text) that has text with a set max-width. The issue arises when the left property of .tooltip is too large, causing its width to shrink du ...

Utilizing the power of Ajax for enhancing table sorting and filtering functionality

Having an issue using JQuery tablesorter to paginate a table with rows fetched from the database. //list players by points (default listing) $result=mysql_query("select * from players order by pts_total") or die(mysql_error()); echo "<table id='li ...