Wednesday, 15 March 2017

Add an array object to an object in javaScript [on hold]

I try adding some elements to an attribute of a object and the attribute is an array but it did not work. Suppose we have a array of objects containing a source object and a target object.

[ { source: 0, target: 1},
  { source: 0, target: 2 },
  { source: 3, target: 4 } ]

Now I want to add a third attribute station to the first element of the array and the result should be

[ { source: 0, target: 1, station: [{name: "station0", price: "3"},{name: "station1", price: "4"}] },
  { source: 0, target: 2 },
  { source: 3, target: 4 } ]

Here is my code

links[0]['station']=[];
    links[0]['station'].push({
      name: "station0",
      price: "3"
    });
    links[0]['station'].push({
      name: "station1",
      price: "4"
    });

It is a very simple javaScript code but it did not work. After run this code in console, the link becomes:

[ { source: 0, target: 1, station: [ [Object], [Object] ] },
  { source: 0, target: 2 },
  { source: 3, target: 4 } ]



via SHE

No comments:

Post a Comment