I want to insert one or more attributes into the existing JSON. Here's the basic format.
我想在现有的JSON中插入一个或多个属性。这是基本格式。
var resultData = {
"result" : "OK",
"data" : [
{"name1" : "value1"},
{"name2" : "value2"}
]
};
And I want to insert {"name3" : "value3"} into the end of the data field. The result should look like this.
我想在数据字段的末尾插入{“name3”:“value3”}。结果应该是这样的。
var resultData = {
"result" : "OK",
"data" : [
{"name1" : "value1"},
{"name2" : "value2"},
{"name3" : "value3"}
]
};
How do I do this? I know how to add an attribute to the resultData or resultData.result or resultData.data.name1 or etc. However, I couldn't find a way to add an attribute to the resultData.data.
我该怎么做呢?我知道如何将属性添加到resultData或resultData.result或resultData.data.name1等。但是,我找不到向resultData.data添加属性的方法。
2 个解决方案
#1
0
You can do:
你可以做:
resultData.data[3] = {"name4" : "value4"}
That would add a new element on the 4th position. And like Sigorilla just answered before me, .push()
will always add it one the end of your object.
这将在第4位增加一个新元素。就像Sigorilla刚刚在我面前回答的那样,.push()总会在你对象的末尾添加它。
You don't need to do resultData["data"].push()
though, as you can just use resultData.data.push()
I think.
你不需要做resultData [“data”]。push(),因为你可以使用resultData.data.push()我想。
#2
1
You can use push()
: resultData["data"].push({"name3": "value3"});
你可以使用push():resultData [“data”]。push({“name3”:“value3”});
#1
0
You can do:
你可以做:
resultData.data[3] = {"name4" : "value4"}
That would add a new element on the 4th position. And like Sigorilla just answered before me, .push()
will always add it one the end of your object.
这将在第4位增加一个新元素。就像Sigorilla刚刚在我面前回答的那样,.push()总会在你对象的末尾添加它。
You don't need to do resultData["data"].push()
though, as you can just use resultData.data.push()
I think.
你不需要做resultData [“data”]。push(),因为你可以使用resultData.data.push()我想。
#2
1
You can use push()
: resultData["data"].push({"name3": "value3"});
你可以使用push():resultData [“data”]。push({“name3”:“value3”});