Pushing Objects Inside JSON Array
I need to push a new ID for my data array. If I try pushing into data it creates one more object but not adding into the array for each. Data: [{'devices':{'dID':'TLSM01'},'uuid':
Solution 1:
data
is an array containing objects. If you want to add a property to each object you have to iterate over the array.
You need to add a new property to the object devices
which is not an array thus you cannot use .push()
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);
Solution 2:
If your "final result" is the result you want to achieve, you don't want to push anything. You're just setting a new property on the entries that already exist in the array. So, loop through and do that:
data.forEach(function(entry) {
entry.EntityID = "12458412548";
});
(Or a simple for
loop.)
If you're using ES2015+ syntax, you could use an arrow function:
data.forEach(entry => entry.EntityID = "12458412548");
...or a for-of
loop:
for (const entry of data) {
entry.EntityID = "12458412548";
}
Solution 3:
var jsonObj = [{"devices":{"dID":"TLSM01"},"uuid":"e863c776-f939-4761-bbce-bf0501b42ef7"},
{"devices":{"dID":"TLSM01"},"uuid":"5a0cd70d-891d-48d8-b205-e92e828ac445"}];
jsonObj.map(item => item.devices["EntityID"] = "12458412548");
console.log(jsonObj);
Post a Comment for "Pushing Objects Inside JSON Array"