合并两个数组以使用JS模板(MustacheJS,Handlebars,Dust)

时间:2018-01-31 12:34:40

标签: javascript arrays json handlebars.js underscore.js

我正在链接到一个外部JSON文件,并希望将其中的两个数组转换为一个单独的数组,以便与JS模板框架(如MustacheJS,Handlebars,Dust等)一起使用。

这似乎可以在Underscore中使用extend,但我发现了另一种称为concat的可能性,但这似乎只在两个单独的数组上展示而不是一个文件https://www.w3schools.com/jsref/jsref_concat_array.asp

是否可以合并来自单个源的两个数组以用于JS模板?

这是JSON http://myjson.com/kjs8l

所以从本质上说,转换:

[
  [
    {
      "productimage": "https://c.static-nike.com/a/images/t_PDP_864_v1/f_auto/i0lfddlghaiwfqlvlqay/air-vortex-shoe-fmq6pS.jpg",
      "producturl": "https://www.nike.com/gb/t/air-vortex-shoe-fmq6pS"
    },
    {
      "productimage": "https://c.static-nike.com/a/images/t_PDP_864_v1/f_auto/cmuof8adhfipkvd0f43r/air-max-95-shoe-XPTbV2mM.jpg",
      "producturl": "https://www.nike.com/gb/t/air-max-95-shoe-XPTbV2mM"
    }
  ],
  [
    {
      "sitename": "Nike",
      "sitetitle": "Nike. Just Do It.. Nike.com",
      "siteurl": "https://www.nike.com/gb/en_gb/"
    }
  ]
]

[
    {
      "productimage": "https://c.static-nike.com/a/images/t_PDP_864_v1/f_auto/i0lfddlghaiwfqlvlqay/air-vortex-shoe-fmq6pS.jpg",
      "producturl": "https://www.nike.com/gb/t/air-vortex-shoe-fmq6pS"
    },
    {
      "productimage": "https://c.static-nike.com/a/images/t_PDP_864_v1/f_auto/cmuof8adhfipkvd0f43r/air-max-95-shoe-XPTbV2mM.jpg",
      "producturl": "https://www.nike.com/gb/t/air-max-95-shoe-XPTbV2mM"
    }
    {
      "sitename": "Nike",
      "sitetitle": "Nike. Just Do It.. Nike.com",
      "siteurl": "https://www.nike.com/gb/en_gb/"
    }
]

1 个答案:

答案 0 :(得分:0)

因此,假设您在JS中读取文件,那么您可以使用concat方法:

var arrays = [
[
    {
      "productimage": "https://c.static-nike.com/a/images/t_PDP_864_v1/f_auto/i0lfddlghaiwfqlvlqay/air-vortex-shoe-fmq6pS.jpg",
      "producturl": "https://www.nike.com/gb/t/air-vortex-shoe-fmq6pS"
    },
    {
      "productimage": "https://c.static-nike.com/a/images/t_PDP_864_v1/f_auto/cmuof8adhfipkvd0f43r/air-max-95-shoe-XPTbV2mM.jpg",
      "producturl": "https://www.nike.com/gb/t/air-max-95-shoe-XPTbV2mM"
    }
  ],
  [
    {
      "sitename": "Nike",
      "sitetitle": "Nike. Just Do It.. Nike.com",
      "siteurl": "https://www.nike.com/gb/en_gb/"
    }
  ]
];
var mergedArrays = [];
for (var i = 0; i < arrays.length; i++){
    mergedArrays=mergedArrays.concat(arrays[i]);
}
console.log(mergedArrays);

请参阅:https://jsfiddle.net/91nmx4uh/

这是你想要的吗?