-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?

1
  • 2
    This is not at all specific to Angular or TypeScript. Commented Nov 18, 2017 at 9:06

2 Answers 2

1

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

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.