Create a JSON array of objects and dynamically append new items to it

I'm feeling a bit lost and frustrated at the moment. I'm attempting to initialize a JSON Array and dynamically add JSON Objects to it during runtime, but something isn't clicking for me.

Let's say I receive a list of repeated values from the server like this:

"employees":[
    {"firstName":"John", "lastName":"Doe"},
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]

My goal is to create an array of objects and populate them with these values.

This is how I'm trying to start my array:

var myArr = []; 

and then I want to add objects with properties to it dynamically, as shown below.

var myobj = {}

for(int i=0;i<length;i++)
{
myobj[i].name = serverrespOBJ.name;
myobj[i].lastName= 'serverrespOBJ.lastname';
myArr.push(myobj)
}

However, I keep getting an error saying name cannot be added to undefined, which leads me to believe I'm not adding items to the object correctly.

I've been searching for examples to help clarify things, but haven't had much luck. Any assistance would be greatly appreciated.

Thank you

Answer №1

Here is an example of what you might need:

let dataList = { staff: [] }   // starting off as empty

dataList.staff.push( {
    firstName: 'Emily',
    lastName: 'Smith'
} );

Answer №2

To begin, initialize the object or array you wish to manipulate dynamically. For example:

var myArray = [], myObject = {};

Next, you can add elements to them like so:

myArray.push(10);
myObject.new = 10; // or myObject['new'] = 10;

For a more advanced scenario:

myArray.push(myObject); //[10, {'new':10}] --> observe our object in the array

Answer №3

To create a new JSON object, you can do it like this:

var newObj = {};
newObj.people = [];
newObj.people.push({"firstName":"Alice", "lastName":"Smith"});

Alternatively, to add data to an existing object:

var jsonObj = {
    "people":[
        {"firstName":"John", "lastName":"Doe"},
        {"firstName":"Mary", "lastName":"Jones"},
        {"firstName":"Sarah", "lastName":"Taylor"}
    ]
};

jsonObj.people.push({"firstName":"Alice", "lastName":"Smith"});

console.log(jsonObj);

Answer №4

Take a look at this code snippet on JSFiddle - http://jsfiddle.net/FamBn/1/

HTML:

<input type="text" id="firstname" />
<input type="text" id="lastname" />
<input type="submit" id="add" />
<div id="dsp"></div>

JS:

var employees=[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
];

$('#add').click(function(){
    var fname=$('#firstname').val();
    var lname=$('#lastname').val();
    employees.push({
        firstName: fname,
        lastName: lname
    });
    var output = '';
    for (var i=0; i<employees.length; i++) {
        output += "FirstName: " + employees[i].firstName + " LastName: " + employees[i].lastName;
    }
    $('#dsp').html(output);
    console.log(employees);
});

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

What is the best way to retrieve a response from a modal dialog using jQuery?

Is there a way to utilize an add-in such as simple-modal or the dialog add-in in the UI kit to achieve AJAX interaction with the server? I am looking for a solution that allows the modal to communicate with the server and return the result back to the ca ...

When refactoring docxtemplater on the server, the request JSON object is no longer accessible in the doc.setData() method

I've been working on refactoring some code in my Node server to remove docxtemplater. The req.body json object is functioning properly and I can even print it inside the doc.setData() method. However, when I try to launch the server, I encounter this ...

What sets apart 'hasClass' from 'is'? Additionally, is there a substitute to retrieve a Jquery element instead?

Similar Question: jQuery .hasClass() vs .is() Sample HTML code: <div class="results"> <div class="table"> <form class="tr" action="#" method="post"> <div class="td"> <input class="dat ...

React-router causing issues with Redux integration

Currently, I'm utilizing the following libraries: react v16.2.0, react-redux v5.0.7, react-router-dom v4.2.2, redux v3.7.2 The main goal is to update some properties within the Auth component and have these changes reflected when the user visits the ...

Stop the npm start command with a specific error message if the file is not found in the repository

Can the npm start process be stopped or cancelled if a specific file is not found in your codebase? I am looking to end the process if the file dev-variables.js is missing, preferably displaying a custom error message like "You are missing the dev-variabl ...

What is the best way to handle a JSON arraylist in a Node.js environment?

Looking to extract and manipulate a specific data format in Node.js? Here is the data structure: {"orderSummary":[ { "name":"Wine", "ProductPrice":"500", "ProductQuantity":"2", "ProductCost":"1000", "SellerId":"2" },{ ...

The steps to properly load "child.vue" into the correct position within "parent.vue" are as follows

Currently I am developing a single page web application using Vue.js. This app consists of 4 "page.vue" files, each with a right and left child .vue component nested inside. For instance, the Page1.vue file is structured as follows (omitting style and scr ...

Using MongoDB to push elements into nested arrays

Currently, I am working on my food blog and aiming to create a specific structure for the food recipes stored in my database. recipes : [ {mainCategoryRecipe1: {...}}, {mainCategoryRecipe2: {...}}, subcategory1: [ {recipe1: {...}} ] ] I have a for ...

Encountering the error 'Cannot read property 'length' of undefined' while attempting to fetch data from a URL using node.js

While attempting to create a Discord-Bot capable of looking up definitions on urbandictionary, I encountered an error after trying to fetch the json from their api. const args = Array.prototype.slice.call(commandArgs); if (!args.length) { return m ...

"I'm looking for a solution on integrating Osano CookieConsent into my Next.js application. Can

I'm facing a bit of a challenge with incorporating the Osano Cookie Consent JavaScript plugin into my nextjs app. I've been attempting to set up the cc object by initializing it in the useEffect of my root landing page: const CC = require( " ...

Learn how to efficiently import data into d3.js from several JavaScript arrays, and create a dynamically updating chart without the need to refresh the page

I currently have two arrays: one is a list of numbers called nums, and the other is a list of strings titled places. For example: nums=[1,2,3,4,5] places = ["house","gym", "work", "school", "park"] Both arrays are the same length. I am looking to crea ...

Tips for maintaining a scrollable Material-UI Table with dynamic height?

I'm encountering an issue with the Material-UI Table component in terms of its size and scrollability. Summary: The Material-UI table only becomes scrollable when its parent has a fixed size. If I set the size to 100% to fit the parent, it overflows. ...

What methods can be used to control the URL and back button in a web application designed similar to an inbox in Gmail?

Similar Question: Exploring AJAX Techniques in Github's Source Browser In my application, there are essentially 2 main pages: The main page displays a list of applications (similar to an inbox) The single application page is packed with various ...

The ideal login page design

I apologize for my lack of knowledge in React, but I am quite new to it and have been struggling with this issue for days. I am having trouble creating a login page in ReactJS. Here is the code in my app.js: import React from 'react'; import {Ha ...

Creating a JSON document with a specific structure using Java

I am currently working on generating a JSON file using Java in a specific format. To clarify, let's assume that I want the JSON file to be structured like this: { "resource":[{"name":"Node1"}], "literals":[{"literal":"A", "B", "C", "D"}] } Essentia ...

(Java) Algorithm for finding numbers divisible by a given number and storing them in an array for later printing

I am trying to create a method that will identify numbers divisible by a specific number and store them in an array for later retrieval. Here is what I have so far: int [] divider(int n) { int [] result = new int[20]; for (int i = 0; i <= n; i+ ...

Sending the form without triggering a new window or tab

My goal is to submit a form using Ajax so that it doesn't open a new tab every time I submit it, which can be quite annoying especially when creating multiple images. The current method of submitting the form works fine, but it opens a new tab each t ...

Tips for customizing the name and description of your Firefox SDK Add-on for localization

Currently, I am working on creating a Firefox add-on and am looking to localize the name and description of the add-on. This information is displayed to users in the Add-ons Manager menu. Unfortunately, the resources I have found online only cover prefere ...

Is the z-index feature not functioning as anticipated?

I'm currently working on a project involving a book that flips on click on both sides. The process involves checking the direction when a page is clicked and flipping it to the left if it's not to the right. Additionally, I adjust the z-index to ...

Incorporating SOAP Service into AngularJS Using AngularJS Data Model

As an experienced Flex Developer diving into the world of AngularJS, I must admit, it's quite confusing!!! Currently, my focus is on making a service call to my backend server (located on the same domain) using a SOAP WSDL Request and populating the ...