-3

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?

Christofer Eliasson
  • 32,939
  • 7
  • 74
  • 103
firebird
  • 3,461
  • 6
  • 34
  • 45

3 Answers3

6
for(var i = 0; i < arry.length; i++)
{
  arry[i].prop = "value";
}
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
2

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 recommend 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.com/

nuala
  • 2,681
  • 4
  • 30
  • 50
1

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.com/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.

Community
  • 1
  • 1
Nathan
  • 11,814
  • 11
  • 50
  • 93
  • This is also not an example of JSON. E.g. keys have to be double quoted and in fact it's not answering the question. firebird wants to extend the objects inside the array not the array itself. – nuala Apr 08 '12 at 21:47
  • I know what JSON is, I use it everyday with AJAX and PHP. I did misunderstand the question though (I thought firebird wanted to just add something to the array, didn't read the whole thing). – Nathan Apr 08 '12 at 21:53
  • Sorry didn't meant to virtually puke in your garden. I just meant to be clear and strict since the OP seems quite confused. Nothing personal :) – nuala Apr 08 '12 at 21:57