admin管理员组文章数量:1405586
I have the following array:
var arry = [{title='Test'}, {title='Test2'}, {title='Test3'}];
I want to add a new property to each of the objects in the array. What is the fastest way of doing this?
I have the following array:
var arry = [{title='Test'}, {title='Test2'}, {title='Test3'}];
I want to add a new property to each of the objects in the array. What is the fastest way of doing this?
Share Improve this question edited Apr 8, 2012 at 21:36 Christofer Eliasson 33.9k7 gold badges77 silver badges103 bronze badges asked Apr 8, 2012 at 21:35 firebirdfirebird 3,5216 gold badges36 silver badges47 bronze badges 03 Answers
Reset to default 6for(var i = 0; i < arry.length; i++)
{
arry[i].prop = "value";
}
Given no further information: hands down and String manipulation.
Before every occurrence of }
you insert foo='bar'
I feel like mentioning this is a terrible solution and if the structure of the array is not 100% rigid it will explode by the next update. Anyway it's a nice example to see what's happening "under the hood"
However in order to get a valid JSON String you have to enclose keys and string values with double qoutes.
Anyway I remend you to get a JSONParser and start working with objects then you have a more robust solution e.g. Matthew posted it.
And here's the example of valid JSON
[
{
"title": "Test"
},
{
"title2": "Test2"
},
{
"title3": "Test3"
}
]
http://jsonlint./
Here's an example of some valid JSON:
[
{
"title1": "hey, this is test one"
},
{
"title2": "hi, test two"
},
{
"title3": "what's up, test three"
}
]
What you posted wasn't JSON.
This answer may help you: https://stackoverflow./a/617051/507629
To add something to an array you can just use .push()
method, for example:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
Learn more about .push
here.
本文标签: javascripthow to add new property to json arrayStack Overflow
版权声明:本文标题:javascript - how to add new property to json array? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744241636a2596815.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论