使用密钥在Javascript中从两个数组创建JSON

时间:2017-05-17 13:53:27

标签: javascript arrays json

所以我想说我在JavaScript中有两个数组。 第一个包含标题

do{
  let str = try String(contentsOf:personUrl!)
  print(str)
}catch let error{
  print(error)
}

第二个包含指向这些页面的链接

var titles = [ "welcome page", "how it works", "about us"]

我想创建一个json,其中包含来自这两个数组的“title”和“link”键,如下所示:

var links = [ "/home", "/howitworks", "/about"]

有谁知道怎么做?

1 个答案:

答案 0 :(得分:0)

假设两个数组的长度始终相同:

(文档)$。就绪(函数(){

var titles = [ "welcome page", "how it works", "about us"];

var links = [ "/home", "/howitworks", "/about"];


var objects = {};
objects['source'] = [];
for (var i=0; i < titles.length; i++) {
  var obj = {};
    obj['title'] = titles[i];
  obj['link'] = links[i];
  objects['source'].push(obj);
}
alert(JSON.stringify(objects));
});