推送JSON数组中的对象

时间:2017-05-02 07:09:26

标签: javascript arrays json

我需要为我的数据阵列推送一个新的ID。如果我尝试推入数据,它会再创建一个对象,但不会为每个对象添加数组。

数据:

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

需要添加数据:

{"EntityID":"12458412548"}

最终结果:

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

代码:



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);




3 个答案:

答案 0 :(得分:1)

data是一个包含对象的数组。如果要为每个对象添加属性,则必须迭代数组。

您需要向对象devices添加新属性,该对象不是数组,因此您无法使用.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);

答案 1 :(得分:0)

如果您的“最终结果”是您想要达到的结果,那么您不想推送任何东西。您只是在数组中已存在的条目上设置新属性。所以,循环并做到这一点:

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

(或简单的for循环。)

如果您使用的是ES2015 +语法,则可以使用箭头功能:

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

...或for-of循环:

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

答案 2 :(得分:0)

<强> DEMO

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);