合并两个json文件并保持相同的JavaScript结构

时间:2018-10-24 22:33:32

标签: javascript arrays json

在尝试创建一个包含我抓取的网站中的信息的JSON时遇到一些问题。我创建了两个文件,它们都具有相同的结构。我想将它们放在一个JSON中,并为两者保留相同的结构。我怎样才能做到这一点?

我的文件如下:

[
 {
   name: 'Jed',
   age: 23
   home: [
          {address: 5th AV 123
           coordinates: [{lat:12324,
                          long:1231
            }
          ]
        }
  ]

我有10个结构相同,但每个文件的信息不同。如何创建包含全部10个内容的主JSON?

2 个答案:

答案 0 :(得分:0)

您可以使用函数Array.prototype.concat将对象附加到特定数组。同样,使用Spread syntax将元素作为参数传递。

let array = anArray.concat(...anotherArray);

或按照以下方式传递多个数组

let anArray = [{    name: 'Jed',    age: 23,    home: [{        address: "5th AV 123",        coordinates: [{            lat: 12324,            long: 1231        }]    }]}, {    name: 'Ele',    age: 36, home: [{        address: "5th AV 123",        coordinates: [{            lat: 12324,            long: 1231        }]    }]}],
    anotherArray = [{    name: 'Rick',    age: 21,    home: [{        address: "5th AV 123",        coordinates: [{            lat: 12324,            long: 1231        }]    }]}, {    name: 'Jade',    age: 42, home: [{        address: "5th AV 123",        coordinates: [{            lat: 12324,            long: 1231        }]    }]}],
    furtherArray = [{    name: 'Enr',    age: 21,    home: [{        address: "5th AV 123",        coordinates: [{            lat: 12324,            long: 1231        }]    }]}, {    name: 'John',    age: 42, home: [{        address: "5th AV 123",        coordinates: [{            lat: 12324,            long: 1231        }]    }]}];

console.log(Array.prototype.concat.call(anArray, ...anotherArray, ...furtherArray));
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

您可以创建以下内容:

MainJson = [
              [
                 [Information From Site -1 related to A], 
                 [Information From Site -2 related to A]
              ], 
              [
                 [Information From Site -1 related to B],
                 [Information From Site -2 related to B]
              ]
           ]