-2

Written in Javascript:

var data =
 [
  {
    value: 30,
    color: "blue"
  }
 ]

I want to push and remove some values from it.

I tried:

data.push (10, "red")
data.push (111, "green")
data.push (1112, "blue")

console.log (data)
console.log (data[0].value)
console.log (data[1].value)

which resulted in:
qml: [[object Object],10,red,111,green,1112,blue]
qml: 30
qml: undefined

The first value present by default in the structure is not shown in console with first print.
I am not able to see the value of the first pushed item with third print.

Christian Schnorr
  • 10,768
  • 8
  • 48
  • 83
Aquarius_Girl
  • 21,790
  • 65
  • 230
  • 411
  • @Cerbrus have edited it. now reopen please. – Aquarius_Girl Jul 13 '15 at 07:40
  • `data` is an array. How is it supposed to know you want to push an object to it, when you're just pushing a string and a number? You're going to have to push the actual object, instead: `data.push({ value: val, color: 'color'})`. – Cerbrus Jul 13 '15 at 07:55
  • @Cerbrus thanks for the answer. Why have you not opened the question yet? Isn't it different? Is push method shown somewhere in that linked thread? – Aquarius_Girl Jul 13 '15 at 08:01
  • Most of the methods used to access arrays of objects are described in that other question. As such, I think it's a good idea to keep the link for future visitors. – Cerbrus Jul 13 '15 at 08:06
  • @Cerbrus pushing method is not shown there. You can keep the link in this thread and atleast open it. – Aquarius_Girl Jul 13 '15 at 08:16

2 Answers2

2

You should push new values like this :

data.push({value : 10, color: 'green'}).

Your JS data is an array of object so when you want to push a new value into it, you need to push an object using the syntax { field1: value1 ... }

You also can write a function the job for you :

function add_value(data,v,color) {
   data.push({value : v, color : c});
}
alifirat
  • 2,899
  • 1
  • 17
  • 33
0

Your array data contains an object as it's items, so I would assume you'd want to do something like this if you were going to push to the array:

data.push({value : 10, color: 'red'});
TryinHard
  • 4,078
  • 3
  • 28
  • 54