0
    var fruits = [];
        fruits[0] = {name:"apple", stock:"1box"}
        fruits[1] = {name:"banana", stock:"2box"}
        fruits[2] = {name:"banana", stock:"3box"}

so in case of this object is there any simple way to add new field inside of list like this? for example

fruits[0] = {name:"apple", stock:"1box", **taste:"good"**}

like this.

i tried create new template and copy original data and paste to the new template, for example

function fruit_2(name, stock, taste){
this.name = name;
this.stock = stock;
this.taste = taste;
}//create new template

and re-add element from the fruit[0] and then fruit[1] to new template like this

but i was wondering if there is easier or faster way.

thank you for reading my question.

i will appreciate any help! thanks!

Liam
  • 27,717
  • 28
  • 128
  • 190
John_potato
  • 105
  • 1
  • 4
  • 2
    `fruits[0].taste = "good"` – Keith Oct 19 '17 at 08:51
  • It is unclear as to what output are you looking for. What should be the end result? – gurvinder372 Oct 19 '17 at 08:52
  • @gurvinder372 His title is slightly miss-leading, he's not asking how to add a new object, more like add a new property to an object that's part of an array. – Keith Oct 19 '17 at 08:55
  • 2
    Some notes on language `{}` is an **object**, `[]` is an **array** `obj.something` `something` is a **property** of the **object** `obj`. What you call a template is a **constructor function**. – Liam Oct 19 '17 at 08:57
  • thank you all for comments! i am newbie and still learning javascript, so i must have misuse terms! thanks for pointing out! i have many things to learn haha! – John_potato Oct 20 '17 at 00:27

3 Answers3

3

I add an taste element to each object, and fill it with the value "good"+ index of the element. Here is a simple demo:

var fruits = [];
fruits[0] = {name:"apple", stock:"1box"};
fruits[1] = {name:"banana", stock:"2box"};
fruits[2] = {name:"banana", stock:"3box"};
        
for(var index=0;index<fruits.length;index++){

    fruits[index].taste="good "+index;

}

console.log(fruits);
Liam
  • 27,717
  • 28
  • 128
  • 190
Mehdi Bouzidi
  • 1,937
  • 3
  • 15
  • 31
0

Easiest way to append is either use:

fruits[0]["taste"] = "good";

or:

fruits[0].taste = "good";
Sam
  • 608
  • 4
  • 11
0

The easiest way to add a property to existing object for each element in array is to itterate over the array and set the property to the desired value using

element[index].desiredProperty = desiredValue;

For example see following fiddle: https://jsfiddle.net/to70xe4j/1/

plmn
  • 46
  • 3