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?

2
  • check _.zipObjectDeep for this. Commented May 17, 2017 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. Commented May 17, 2017 at 14:37

1 Answer 1

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));
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.