Inserting items into a JSON array

Is there a way to add a new ID to my data array without creating a new object for each addition?

Existing Data:

[{"devices":{"dID":"TLSM01"},"uuid":"e863c776-f939-4761-bbce-bf0501b42ef7"},
 {"devices":{"dID":"TLSM01"},"uuid":"5a0cd70d-891d-48d8-b205-e92e828ac445"}]

New Data to Add:

{"EntityID":"12458412548"}

Desired Result:

[{"devices":{"dID":"TLSM01","EntityID":"12458412548"},"uuid":"e863c776-f939-4761-bbce-bf0501b42ef7"},
 {"devices":{"dID":"TLSM01","EntityID":"12458412548"},"uuid":"5a0cd70d-891d-48d8-b205-e92e828ac445"}]

Code Snippet:

var data = [{
  "devices": {
    "dID": "TLSM01"
  },
  "uuid": "e863c776-f939-4761-bbce-bf0501b42ef7"
}, {
  "devices": {
    "dID": "TLSM01"
  },
  "uuid": "5a0cd70d-891d-48d8-b205-e92e828ac445"
}]
data.push({
  "EntityID": "test"
});
console.log(data);

Answer №1

data is an array that contains a list of objects. In order to add a new property to each object within the array, you must iterate through each object.

In this case, you are trying to add a new property to the object devices, which is not an array. As a result, you cannot use the .push() method to accomplish this task.

var data = [{"devices":{"dID":"TLSM01"},"uuid":"e863c776-f939-4761-bbce-bf0501b42ef7"},{"devices":{"dID":"TLSM01"},"uuid":"5a0cd70d-891d-48d8-b205-e92e828ac445"}];

data.forEach(d=>d.devices['EntityID']="test");

console.log(data);

Answer №2

If you want to achieve your desired "final result", there's no need to force anything. Simply add a new property to the existing entries in the array by looping through them:

data.forEach(function(entry) {
    entry.EntityID = "12458412548";
});

(Alternatively, you could use a basic for loop.)

If you prefer using ES2015+ syntax, you have the option of using an arrow function:

data.forEach(entry => entry.EntityID = "12458412548");

...or utilize a for-of loop:

for (const entry of data) {
    entry.EntityID = "12458412548";
}

Answer №3

CLICK HERE FOR DEMO

let data = [{"devices":{"dID":"TLSM01"},"uuid":"e863c776-f939-4761-bbce-bf0501b42ef7"},
 {"devices":{"dID":"TLSM01"},"uuid":"5a0cd70d-891d-48d8-b205-e92e828ac445"}];
 
data.map(item => item.devices["EntityID"] = "12458412548");

console.log(data);

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

Using radio buttons and a price slider, a unique jQuery filter for products can be

I have successfully implemented basic functionality to filter products based on price (slider) and radio boxes. However, the current filter system uses OR logic, but I need it to use AND instead. For instance, I want to find a product that is from Brand1, ...

I am encountering an issue where I am sending an AJAX request to a PHP file with the datatype set as JSONP, but I

When I click on the submit button, I am sending a variable to sendmail.php. However, PHP is showing that 'contactname' is undefined. Why is this happening? Here is the code snippet: var name = document.getElementById('stream_cotactname&apo ...

Troubleshooting Key Press Issues with Bootstrap 5 Dropdown and Collapse Feature

Exploration In my quest to create a dynamic Bootstrap (5) Navigation bar/menu with animated sub-menus, I stumbled upon a solution that seems to fit the bill perfectly. By employing data-bs-toggle="collapse" instead of 'dropdown', I dis ...

Converting a PySpark dataframe into a properly formatted JSON output

I've been attempting to transform a dataframe into a properly formatted json file, but I haven't had any success yet. When I try this: fullDataset.repartition(1).write.json(f'{mount_point}/eds_ckan', mode='overwrite', ignoreN ...

Unable to destructure the 'reservations' property from 'this.props.reservation' due to its undefined status, implementing a filter in ReactJs

I am having trouble retrieving reservations from my server when I try to access the rooms. I have followed a similar method but for some reason, I can't seem to access them. My goal is to retrieve reservations from the server and filter them based on ...

Discovering a device's model using JavaScript

How can I use Javascript to redirect users to different download pages based on their device model? ...

Ways to extract individual values from a Json Array and utilize them individually

I have a JSON data structure that I need to parse and separate each field into different arrays, so that I can use them individually. For instance, I want to split my data into two rooms: room 1 and room 2. After separating the data, I need to format it a ...

Guide to implementing the onchange event in JavaScript for this specific scenario

How can the onchange event be utilized in this scenario using JavaScript? First, input data into the input with id="one". Subsequently, the data in the input with id="two" will be updated to match the data in the input with id="one". However, when the da ...

The router.navigate() function seems to be malfunctioning as it is not working as

I have a method defined as follows: private redirect(path: string): void { this.router.navigate([path]); } This method is called within another method like so: private onError(error: any): void { switch (error.status) { case 401: / ...

Struggling to retrieve information from a JSON file and display it within a component?

After accessing the JSON data and storing the necessary values in a dictionary named details, I am encountering an issue where the values are displayed when console logged from inside the function but appear as undefined when console logged in the parent f ...

I am looking to display the dynamic response in Angular8 in real-time

Looking for ways to dynamically bind JSON data to HTML page elements like labels and textboxes using Angular. Any insights or recommendations are welcome. { "model": "abcd.abilivcdcty.configuration", "typeId": "abcd.edge.modules.opcuamodule. ...

What is the best way to showcase a singular item from response.data?

Below is the controller I have set up to display details of a single book from my collection of json records .controller('BookDetailsController', ['$scope','$http','$stateParams',function($scope,$http,$stateParams){ ...

Is there a method to generate an endless carousel effect?

Hello, I am trying to create an infinite carousel effect for my images. Currently, I have a method that involves restarting the image carousel when it reaches the end by using the code snippet progress = (progress <= 0) ? 100 : 0;. However, I don't ...

What is the best way to enhance the class following this condition in JavaScript?

Initially, the original script worked perfectly with just one class being added: function check_btn_charge() { if (parseInt(jQuery(".total-change-price").text()) >= 0) { jQuery(".btn-action-save-charge"+"&nbsp;"+"btn-danger" ...

What could be causing my Ionic button to not initialize in the expected state while using ngIf with a boolean property connected to an Ionic checkbox?

I'm currently in the process of setting up a list of ingredients with checkboxes and conditional buttons, but I'm facing some challenges with the default state. Ideally, I only want the button to be visible when the checkbox is unchecked so that ...

What is the best way to display compiled Transcluded HTML in Angular?

I am facing a challenge in trying to display customized HTML content using Angular directives for nesting divs multiple times. When I execute the code below, the transcluded tag is displayed correctly but the browser output shows the string text " ". I att ...

Calculate the outer product of arrays with varying dimensions

Consider two arrays X,Y for which the outer product is needed to be calculated on their last dimension. For example, result[:,i,j]=X[:,i]*Y[:,j] when both X,Y are 2-dimensional. If I encounter situations where the dimensions of X,Y are unknown and could v ...

issues arise when using array_merge, serialize, and unserialize functions in PHP

I am faced with the following task: Insert an associative array into a database field so that it can be reused as an associative array. [Completed using serialize($associativeArray)] Retrieve the associative array from the database and view it as an arra ...

Error: The property "indexOf" cannot be accessed because n is not defined

After rendering a page and retrieving data from Firebase upon clicking a button, I encounter an error upon refreshing the page: Unhandled Runtime Error TypeError: can't access property "indexOf", n is undefined Source pages\[id].js (1 ...

Tips for avoiding Netlify's error treatment of warnings due to process.env.CI being set to true

Recently, I encountered an issue with deploying new projects on Netlify. After reviewing the logs, I noticed a message that had never appeared during previous successful deployments: The build failed while treating warnings as errors due to process.env.CI ...