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 0
Add a ment  | 

3 Answers 3

Reset to default 6
for(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