Vineonardo
Vineonardo

Reputation: 183

AngularJS - How to append json to another json object?

So I've to different objects, getting data from different sources. I need to convert them into a single object so that I can ng-repeat them.

object1 = {
"key1":"value one",
"key2":"value two"
}

object2 = {
"key1":"value three",
"key2":"value four"
}

What I need is

object3 = [{
"key1":"value one",
"key2":"value two"},
{
"key1":"value one",
"key2":"value two"}
}];

I tried angular.merge but it only works if the keys are different. In my case, keys are gonna be the same, only data is gonna change.

Can anyone help append object1 to object2 to create something like object3 which is object1+object2.

I tried converting them to json string & concatenating them but it didn't work. Array contact function is not working either.

Upvotes: 2

Views: 6910

Answers (1)

toskv
toskv

Reputation: 31600

This is just vanilla javascript. You want to make an array of from the objects.

var object1 = {
  "key1": "value one",
  "key2": "value two"
}

var object2 = {
  "key1": "value three",
  "key2": "value four"
}

var object3 = []; // empty array

// add the other objects to the array
object3.push(object1);
object3.push(object2);

if your objects are already arrays and you just want to concatenate them, you can use the concat function on arrays.

var object1 = [{
  key: 'abc',
  value: 1
}];
var object2 = [{
  key: 'cbd',
  value: 2
}];

// use the concat function to concatenate the arrays
var object3 = object1.concat(object2);

You can find more about arrays by reading the documentation found here.

If your objects are firebaseArray objects they have their own API. More can be found here.

Upvotes: 3

Related Questions