Tips for incorporating a variable into a JSON object value when dynamically constructing an object

Is there a way to dynamically create an array of objects using a for loop? I have different arrays with values for the key value pairs of these objects. The code snippet I tried is not producing the expected result.

var characters = ['Iron Man', 'Hulk', 'Thor'];
var actors = ['Robert Downey, Jr', 'Mark Ruffalo', 'Chris Hemsworth'];
var objArray = [];

for(let i=0; i<characters.length; i++){
  objArray[i] = {
    character: characters[i],
    actor: actors[i]
  };
}

However, this code is throwing an error and not generating the intended array of objects as shown below:

[
  {
    "character": "Iron Man",
    "actor": "Robert Downey, Jr"
  },
  {
    "character": "Hulk",
    "actor": "Mark Ruffalo"
  },
  {
    "character": "Thor",
    "actor": "Chris Hemsworth"
  } 
]

Answer №1

Another approach is to utilize the map method

var anObj = [];
var charectors = ["Iron Man", "Hulk", "Thor"];
var actors = ["Robert Downey, Jr", "Mark Ruffalo", "Chris Hemsworth"];

const result = actors.map((actor, i) => ({ charector: charectors[i], actor: actors[i] }));
console.log(result)

Alternatively, you can achieve this using a for...of loop

var anObj = [];
var charectors = ["Iron Man", "Hulk", "Thor"];
var actors = ["Robert Downey, Jr", "Mark Ruffalo", "Chris Hemsworth"];

const result = [];

for (let [i, actor] of actors.entries()) {
  result.push({
    charector: charectors[i],
    actor: actors[i],
  });
}
console.log(result);

Answer №2

Embrace the use of : in lieu of = when structuring your for loop. Fundamental object properties assignment

 var myObject = [];
 var superheroes = ['Iron Man', 'Hulk', 'Thor']
 var actors = ['Robert Downey, Jr', 'Mark Ruffalo', 'Chris Hemsworth']
 for(let i=0; i<superheroes.length; i++){
   myObject[i] = {
     superhero : superheroes[i],
     actor : actors[i]
   } 
 }

Answer №3

Insert the values into an array by


anObj.insert({
    charector: charectors[i],
    actor: actor[i]
  })

Answer №4

You've made two mistakes:

  1. The correct assignment separator inside the braces is the colon, not the equal sign.

  2. The name of the second source array should be actors, not actor.

    var anObj = [];
    var charectors = ['Iron Man', 'Hulk', 'Thor']
    var actors = ['Robert Downey, Jr', 'Mark Ruffalo', 'Chris Hemsworth']
    for(let i=0; i<charectors.length; i++){
      anObj[i] = {
        charector : charectors[i],
        actor : actors[i]
      } 
    }
    
    console.log(anObj);

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

Including v-menu in a button causes it to vanish in Vuetify

I am facing an issue with my stepper. Specifically, in step 3, I am trying to add a v-menu to a button but when I do so, the button disappears. Below is the code snippet causing the problem: <template> . . . . <v-stepper-step :complete="e6 > ...

Mastering the Art of Modifying HTML with Node.js

Is it possible to manipulate HTML using Node.js? 1. First, I need to retrieve data from a database. 2. Then, I need to modify or add HTML code within Node. In essence, the goal is to fetch data and integrate it into an HTML file. The JavaScript snippet ...

AJAX is delivering a unique random hash instead of the expected text

I am in the process of developing a live notification script, and I have encountered an issue. Instead of receiving plain text from the external file, the script is returning a random hash... Here is the function responsible for fetching data from test.ph ...

Rails 5 not allow user submission of bootstrap modal form

I am facing an issue with a form inside a modal in my Rails application. When I click on the submit button, nothing happens. How can I use Ajax to submit the modal form and save its content on another page? <button type="button" class="btn btn-primary ...

Modify the CSS when CKEditor is in focus

Implementing CKEditor in a symfony project using the FOS\CKEditor-bundle 1.2. I want to style the entire element containing CKEditor with a border when it is focused, similar to how questions are written or answered on Stackoverflow. By referencing a ...

JavaScript form validation problem: Warning for identical responses in the MOST and LEAST sections

I've encountered a challenge while working on an HTML and JavaScript form for a personality test. The issue revolves around validation, particularly when the form includes multiple questions with both "MOST" and "LEAST" radio button options. One spec ...

How can I recreate this image in 3D using three.js?

I have a tower image' - but i don't know how to replicate this for3dview using thethree.js` any assistance would be greatly appreciated! Here is the image : This is my attempt : $(function () { "use strict"; var container, scene, cam ...

The Express.js server seems to be having trouble rendering a static JavaScript file

Currently, I am in the process of constructing a website and have implemented an express.js server to collect data submitted through a form. Prior to configuring the server, I had already developed the site using static js and css files. Once the connectio ...

Trimming data from model fields in a Node.js application before saving to a PostgreSQL database

While working on my node.js project, I am utilizing the objection.js ORM. So far, everything has been running smoothly. However, I'm looking to implement a feature that will trim all the fields before saving the data in the PostGres database table. In ...

Creating a 3D cube with visual graphics as its faces using Three.js

I've been experimenting with different solutions but haven't had any luck finding a solution online. The error I'm encountering when running my program is: XMLHttpRequest cannot load file:///C:/Users/winst/Documents/Programming%20Projects/Mi ...

Utilizing a JSON object to send data to a C# WebAPI POST endpoint that accepts a parameter of a generic abstract class

I have a generic abstract class that defines the structure of an object to be POSTed to this endpoint. The class is as follows, with an example implementation: public abstract class Animal<T> { public string Name { get; set; } pu ...

Tips to swap selections in a Select2 dropdown box

Is there a way to dynamically clear a Select2 option list and reload it with new data? Despite setting the data as suggested, it seems to only append the new data without clearing the existing options. $("#optioner").select2(); $("#doit").click(functio ...

Retrieving currentUser data using Vue.js, Vuex, Express, and MongoDB

I am currently working on creating a MEVN stack authentication page that displays information about the user who is logged in. After successfully logging in, the router redirects to Home.vue and passes the username as a prop. The onSubmit method in Login. ...

The Power of Json, Ajax, and Javascript

Is there a way to regularly check for updates and update the relevant cell accordingly? I want the updated cell to flash and change color to red/green based on if it is a negative or positive numeric value. I will be using JQuery, Ajax, and JSON... Best ...

AngularJS implemented to trigger a popup alert after a certain duration of time has elapsed since the

Can we create a popup alert that says "Error Contacting Server" when the http request does not receive any response? .controller('items_ctrl',['$scope','$http',function($scope,$http){ $scope.shop_id=localStorage.getItem(" ...

Does AngularJS have a similar function to $(document).ajaxSuccess()?

When working with AngularJS, I am looking to implement a universal ajax loader that does not require integration into each controller to function. In jQuery, this can be achieved through the following code: (function globalAjaxLoader($){ "use strict"; ...

Bringing the Jquery cursor into focus following the addition of an emoji

Looking to add emojis in a contenteditable div but facing an issue with the cursor placement. Here is a DEMO created on codepen.io. The demo includes a tree emoji example where clicking on the emoji adds it to the #text contenteditable div. However, after ...

Extracting data from web pages using JavaScript and PHP

Using the following script, I am able to scrape all the items from this specific page: $html = file_get_contents($list_url); $doc = new DOMDocument(); libxml_use_internal_errors(TRUE); if(!empty($html)) { $doc->loadHTML($html); ...

Adjusting Bootstrap card content on hover

Currently, I am in the process of developing a website that features a list of products presented in bootstrap cards. I am seeking advice on how to dynamically change the text displayed on these cards when a user hovers over them. Specifically, I want to ...

Issue with Jquery event not triggering correctly following ajax data retrieval

This script uses jQuery and Ajax to populate a navigation bar with categories and subcategories dynamically. The first unordered list is static, while the second one is populated after receiving data via Ajax. There are some jQuery events that need to be i ...