0

So let's say that I have two arrays in JavaScript. The first one contains the titles

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

And the second one contains the links to those pages

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

I want to create a json, with the keys "title" and "link" from those two arrays like following:

source:{
 {
  title:"welcome page",
  link:"/home"
 },
 {
  title:"how it works",
  link:"/howitworks"
 },
...
}

Does anyone know how to do that?

Hassen Ch.
  • 1,693
  • 18
  • 31
  • check [_.zipObjectDeep](https://lodash.com/docs#zipObjectDeep) for this. – optimistanoop May 17 '17 at 14:32
  • Thank you for the suggestion @optimistanoop but I'm trying to find to most lightweight and most simple solution without having to import a new library. But again thank you very much for the suggestion. – Hassen Ch. May 17 '17 at 14:37

1 Answers1

0

Assuming both arrays are always the same length:

$(document).ready(function(){

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));
});