How to generate a JSON key-value pair?

I have 2 sets of arrays with the exact same length :

var set1= ["apple", "banana", "orange", "mango", "grape", "kiwi", "pear", "papaya"]
var set2 = ["junglebook", "narnia", "harrypotter", "lordoftherings", "aliceinwonderland", "peterpan", "sherlockholmes", "wizardofoz"]

The desired output would be :

result = [{item:apple,story:junglebook},{item:banana,story:narnia},{item:orange,story:harrypotter},{item:mango,story:lordoftherings},{item:grape,story:aliceinwonderland},{item:kiwi,story:peterpan},{item:pear,story:sherlockholmes},{item:papaya,story:wizardofoz}]

Can anyone assist me with this task?

Answer №1

Implementing map is the way to go:

let updatedArray = initialArray.map((element, idx) => ({ identifier: element, change: secondArray[idx] }));

Answer №2

To accomplish this task, you can utilize the power of Array.map().

Check out a demonstration below:

  var numbers = ["1", "2", "3", "4", "5", "6", "7", "8"];
  var channels = ["abc", "nbc", "cbs", "fox", "hbo", "espn", "tnt", "amc"];
  
  const mergedArray = numbers.map((item, index) => {
    return {number: item, channel: channels[index]}
  });
  
  console.log(mergedArray);

Answer №3

let numbers = ["one", "two", "three", "four", "five", "six", "seven", "eight"];
let channels = ["nbc", "abc", "cbs", "fox", "hbo", "tnt", "mtv", "buzzfeed"];

let combined = [];
for(let j = 0; j < numbers.length; j++) {
    let pairing = {
            numberId: numbers[j],
            channelName: channels[j]
        }
    combined.push(pairing);
}

console.log(combined);

Answer №4

It seems like you're interested in a solution similar to this.

let numbers = ["1", "2", "3", "4", "5", "6", "7", "8"];
let channels = ["discovery", "nationalgeographic", "hbo", "wb", "comedycentral", "pogo", "cnn", "romedynow"];

let result = [];

for (let i = 0; i < numbers.length; i++) {
    result.push({"id": numbers[i], "chan": channels[i]});
}

console.log(result);

Here is the output I have achieved:

[ { id: '1', chan: 'discovery' },
  { id: '2', chan: 'nationalgeographic' },
  { id: '3', chan: 'hbo' },
  { id: '4', chan: 'wb' },
  { id: '5', chan: 'comedycentral' },
  { id: '6', chan: 'pogo' },
  { id: '7', chan: 'cnn' },
  { id: '8', chan: 'romedynow' } ]

Wishing you success!

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

The Material UI component successfully loads the options data list from the server response, however, it fails to return the selected value when an option

My goal is to dynamically populate my country and province select component based on server response data. The process begins with the user selecting a country, which triggers a request to the server using the selected country's id. The server respond ...

Exploring Functionality in JavaScript

Having trouble dissecting the following piece of code and grasping its purpose? How does this illustrate the functionality of functions in JavaScript? Apologies for the beginner question. Feeling lost? Thank you. function combine(central) { for (var ...

React and SASS - issue with checkbox component not being properly aligned with its label

I'm brand new to React and I'm currently in the process of converting a pure HTML page into a React component. How can I adjust the SASS stylesheet to match the original HTML layout? Here is my current React setup (the checkbox displays on the r ...

Retrieve the JQuery element using its ID or class identifier

I need some assistance with retrieving the innerHTML of element number 5 in a JQUERY Object. Can someone provide guidance on how to achieve this? Your help is greatly appreciated. ...

What's with the increased verbosity of mongoose query result objects in the latest version?

After installing my dependencies on a new computer, I noticed that mongoose must have been updated. The informative results from my queries are now appearing in messy outputs with excessive information that is not always useful. It used to be concise and c ...

Navigating with Node.js and angular

I'm struggling with redirecting POST requests using Node.js, Express, and Angular. Typically, we'd use forms like this: index.ejs <!DOCTYPE html> <html> <head> <title>Redirect Example</title> </head> <bo ...

Different method for uploading json documents to Firebase's live database

Recently, while following a Google codelabs tutorial on creating a chat app, I encountered an issue with importing a JSON file into the realtime database. The tutorial can be found at . The instructions were to access the Database section in the Firebase ...

Populate various input fields upon choosing an option from a dropdown list

I'm trying to set up a dropdown menu with multiple options, where selecting an option triggers certain input fields. However, I haven't been able to achieve the desired outcome. Can someone assist me with this, preferably using VanillaJS? Thank ...

What is the best method for merging 24 columns into a single array column in R?

Looking for a more concise solution, I currently have code that consolidates 24 columns of data into a single column array in a dataframe: # Combines values from multiple columns into one using comma as separator. agg_bluetooth_data$twentyfourhours <- ...

Changing a specific string into an array with PHP

Let's tackle a common coding challenge: $string = "[{"006":"BASIC"}, {"007":"ADV"}]"; We are aiming for the final array format: Array( "006" => BASIC, "007" => ADV ) Ini ...

Rotating around the axis of extrusion, Three.js extrudes a 2D face

I am interested in creating a twisting effect during extrusion on a shape, rotating it about the Z-axis like seen in the examples below https://i.sstatic.net/wLF2s.png and here https://i.sstatic.net/Aq7Db.png My attempt at achieving a twisted cube is o ...

Can a new webpage be created without requiring a separate HTML file extension?

Currently working on an assignment that requires creating various pages for a website. I currently have multiple HTML files where I link to each one to open the pages, such as Bagel and Bagel.html. Is there a more effective and efficient way to achieve t ...

The attempt to compare two undisclosed inputs using basic javascript was unsuccessful

In my current project, I am facing an issue with comparing two hidden input HTML elements using JavaScript onclick submit button. Despite the seeming simplicity of the task, it is not working as expected. The function that I have implemented for this purp ...

Using Google App Script for Slides to center-align text within a text box

Currently, I am tackling a project that demands the center alignment of text within a textbox on a google slide using a google app script. The primary objective is to fetch text from a google worksheet and an image from google drive. Subsequently, combine ...

Creating a horizontal navigation bar using localscroll.js in your website is a great way

In my portfolio, I want to create a horizontal navigation with local scroll to showcase a gallery of various pictures. For this, I have a (div id="projects") with links structured like this: <div id="projects"> <ul id="content-slider-inside ...

`Upkeeping service variable upon route alteration in Angular 2`

Utilizing a UI service to control the styling of elements on my webpage is essential. The members of this service change with each route, determining how the header and page will look. For example: If the headerStyle member of the service is set to dark ...

The focal length in THREE.js PerspectiveCamera seems to be miscalculated, which is not aligning with the field of view

When working with THREE.js, one of the fundamental aspects is constructing a camera using a specific function: const camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000); An interesting aspect to consider regarding cameras is the relations ...

Dynamic styling updates on page refresh in Next.js

There is a strange issue with my styling that I can't seem to figure out. I have a NavBar set to be 20vh in height and an image set to be 100% in width. However, whenever I refresh the page, the NavBar height decreases and the image width increases si ...

Discover key/value pairs by using jq that are dependent on another key/value pair

Here is a JSON example data that needs to be manipulated to achieve the desired output specified in the next section. The goal is to parse this data using jq. I aim to use jq for parsing my desired data. { "MetricAlarms": [ { "EvaluationPerio ...

Looking to calculate the sum of each row in a multi-dimensional array using PHP?

After retrieving data from my database and putting it in an array, I attempted to compare each element in the array with the input I entered. Here's a snippet of my code: $query = "select * from caseunder"; $result=mysql_query($query) or die('E ...