-5

my Json looks like

[{"name":"a","value":1},
 {"name":"b","value":2},
 {"name":"c","value":3},
 {"name":"d","value":4}]

Get these Json data to my project by ,

 this.http.get('http://localhost:8000/names')
        .map(response=>response.json())
        .subscribe(data=>{this.names = data});
now I want to add a new object to the existing like

"name":"new","value":5

i tried like this :

for(i in this.alldepartment){}
// alert(i) -> it alerts 3
this.names[++i]["name"]="new";
this.names[++i]["value"]=5;
alert(JSON.stringify(this.names));

But it will not work.I want to become

[{"name":"a","value":1},
 {"name":"b","value":2},
 {"name":"c","value":3},
 {"name":"d","value":4},
 {"name":"new","value":5}]

Is there any solution for this?

Raven
  • 1,453
  • 3
  • 18
  • 29
vinu prasad
  • 169
  • 1
  • 3
  • 13

2 Answers2

1

Solution 1 : data.push({name: "e", value: 5});

Solution 2 (ES6) : this.names = [ ...data, { name: "e", value: 5}];

Ron537
  • 990
  • 1
  • 9
  • 20
0

You can use the push() function of an Array. The push() method adds one or more elements to the end of an array and returns the new length of the array.

this.names = [];
//or in your case
this.names = [{ "name": "a", "value": 1 },
{ "name": "b", "value": 2 },
{ "name": "c", "value": 3 },
{ "name": "d", "value": 4 }];

this.http.get('http://localhost:8000/names')
  .map(response => response.json())
  .subscribe(data => {
    //data => { "name": "e", "value": 5}
    this.names.push(data);
  },
  err=>{
    console.log(err);
  },
  ()=>{
    alert(JSON.stringify(this.names));
  }
);

Hope that helped. You can read up more about this function at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push?v=a

zubair1024
  • 843
  • 8
  • 24