如何将json附加到另一个json对象?

时间:2022-09-25 08:49:48

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.

我需要不同的对象,从不同的来源获取数据。我需要把它们转换成一个对象,这样我就可以对它们进行ng-repeat。

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.

谁能帮助将object1附加到object2以创建object3(即object1+object2) ?

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

我试着将它们转换成json字符串并将它们连接起来,但没有成功。数组接触函数也不工作。

1 个解决方案

#1


3  

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

这只是普通的javascript。您想要从对象中创建一个数组。

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.

如果您的对象已经是数组,并且您只想将它们连接起来,那么您可以在数组中使用concat函数。

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.

如果您的对象是firebaseArray对象,那么它们有自己的API。在这里可以找到更多。

#1


3  

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

这只是普通的javascript。您想要从对象中创建一个数组。

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.

如果您的对象已经是数组,并且您只想将它们连接起来,那么您可以在数组中使用concat函数。

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.

如果您的对象是firebaseArray对象,那么它们有自己的API。在这里可以找到更多。