Generating JSON object in JavaScript by combining data from two arrays using specified keys

If, for instance, I were to have two arrays within JavaScript. The initial one possessing titles

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

And the subsequent array containing the respective links to those pages

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

The aim is to generate a json object utilizing keys "title" and "link" from the aforementioned arrays as illustrated below:

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

Is there anyone that could provide guidance on how to achieve this?

Answer №1

In the scenario where both arrays always have the same length:

$(document).ready(function(){

var categories = [ "best sellers", "new arrivals", "clearance items"];

var urls = [ "/bestsellers", "/newarrivals", "/clearance"];


var dataObjects = {};
dataObjects['items'] = [];
for (var i=0; i < categories.length; i++) {
  var item = {};
    item['category'] = categories[i];
  item['url'] = urls[i];
  dataObjects['items'].push(item);
}
alert(JSON.stringify(dataObjects));
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Modifying the height of an SVG <g> element: A step-by

Is there a way to adjust the height of a g element? Trying to set the height using {params} but it's not responding I made some changes in the comments because the svg is quite large (Scene.js) {/* Transformation */} <g transform="trans ...

Enhanced Button Dropdown Function

I have the following HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Expanding Dropdown Menu</tit ...

Changing the data type of an integer to a string within an Object

I'm working with two arrays of objects. I need to convert the data values in the first format from integers to strings, but I'm struggling to find a simple solution. Is there anyone who can provide assistance? https://i.sstatic.net/mzqWE.png If ...

The data values are transformed following a JSON AJAX POST request with a percentage symbol

I'm facing an issue while developing a slide editor using AJAX. I have a PHP script with multiple functions that can be accessed via different GET parameters. Everything works smoothly until I try to save the slides, at which point the value of transf ...

Guidelines for providing the image file path in an external JavaScript file for creating a Flask API

I am looking to modify the attribute value in the index.html file from an external JavaScript file that is linked to the HTML file. The structure of my folders is as follows: folder structure When I try to specify the path from the HTML file using: {{url ...

Why is it that my for loop produces the accurate result, yet my forEach function fails to do so?

Hey there, I'm new to SO and seeking some guidance. I have a task where I need to create a function with two parameters - an array of strings and a string to potentially match within the array. I've developed two versions of the function: one us ...

fetch and modify data simultaneously in firebase

Is there a way to retrieve a value from a Firebase document and immediately update it? I am familiar with methods for updating documents and retrieving their values separately, but how can I accomplish both in one go? update firebase.firestore().collecti ...

The md-items function is experiencing issues with updating the suggestion list correctly within the md-autocomplete feature of Angular Material

I am currently utilizing md-autocomplete, and I am facing an issue with the md-items not updating the response list correctly from the Service Host - Ajax Call. Here is the HTML Source Code: <md-autocomplete flex required md-input-name="autocomple ...

Guide on integrating JSON and Handlebars partials using Gulp for creating HTML pages

Currently, I am in the process of constructing a static site utilizing Handlebars and Gulp. Here is an overview of my directory setup: app/ content/ intro.json header.json faq.json features.json footer.json ...

momentjs isValid function is providing incorrect results, returning false when it should return true, and vice versa

Incorporating HTML, javascript, and jQuery, I am bringing in a date from MS Excel using "xlsx.full.min.js". To ensure the format remains consistent, I have designated the date field in MS Excel as text. Once imported, I proceed to analyze the table that is ...

The useState setFunction does not alter on OnClick events

My useState element is causing issues because the function doesn't get called when I click on it. I've tried multiple solutions and debugging methods, but it seems like the Click event isn't being triggered no matter what I do. const [moda ...

Step-by-step guide on programmatically closing the Material-UI DropDownMenu

http://www.material-ui.com/#/components/dropdown-menu Having encountered a styling issue, I was compelled to rearrange the order of components within my material-ui DropdownMenu. Nevertheless, some buttons (renderNavLink) are now failing to close the Dro ...

Incorporating JSON Data into a Collection within my Controller

I have read numerous posts that somewhat touch on my situation, but they all leave me feeling perplexed. Currently, I am sending an object via a POST request to my Controller. I have managed to get the post to reach my controller using the following code: ...

Develop a personalized mapping API with a unique image integration for website navigation

Currently, I am in the process of developing a website for my university that will allow users to easily locate all available free food options on campus. My goal is to create a platform where food providers can register their events, have them saved in a ...

The functionality of clicking on Google Visualization table chart to return row/column values is malfunctioning on Mozilla browser

I'm facing an issue with the code below that seems to behave differently in Chrome and Mozilla browsers. In Chrome, when a cell is clicked, the code successfully returns the row / column clicked. However, in Mozilla, clicking a cell does not trigger ...

Break down a string with various delimiters into an array with key-value pairs

Utilizing a module to facilitate the creation of booking orders on my website. This module offers a hook that triggers after a new booking is successfully created. The data I receive is stored in the variable booking_form, which contains the following in ...

Creating a Form Input Field Based on a Selection List

I'm in the process of developing a small app to boost my productivity at work. Currently, I have some html/js code that includes a ul with a search filter. When I select an option, it opens a new tab with relevant text. Ideally, I want the outcome to ...

Having trouble with jQuery scrollTop not working after loading content with ajax?

When the html content is loaded via ajax, I need to scroll to a specific element. This element has the attribute data-event-id="". However, there are instances when the variable $('.timelineToolPanel[data-event-id="'+id+'"]').offset().t ...

What is the process for adding a custom header when making an ajax call in a datatable?

Currently, I am utilizing datatables and need to include a custom header for specific server-side requirements. Can anyone provide guidance on how to send a custom header when navigating to the next or previous pages using jQuery datatables? Additional ...

What defines a quick or sluggish load time when it comes to a webpage?

Recently, I constructed a webpage with multiple JavaScript elements incorporated. I am wondering what constitutes a fast load time versus a slow one. Currently, my load time is averaging around 490ms with four different JavaScript components. Is this con ...