Develop a JSON object with a unique format by combining elements from two separate arrays using JavaScript

I've searched extensively on stack for a solution but couldn't find one, so I'm reaching out here for help:

Let's consider two arrays: one with "keys" and the other with "values"

For example:

keys = [CO2, Blood, General, AnotherKey, ... ]
values = [[2,5,4,6],[4,5,6],[1,3,34.5,43.4],[... [

The goal is to create specific Json structure like this:

[{
        name: 'CO2',
        data: [2,5,4,6]
    }, {
        name: 'Blood',
        data: [4,5,6]
    }, {
        name: 'General',
        data: [1,3,34.5,43.4]
    }, {
         ...
    }, 
}]

I attempted to manipulate strings and encode them as json, but it doesn't seem to be the right approach. I also tried using JSON.PARSE and JSON.stringify without success. If anyone knows the correct way to implement this, please share!

EDIT:

I realized that "name" and "data" are not strings but objects.

Answer №1

Below is a method to achieve the desired result:

keys = ["Dog", "Cat", "Rabbit", "Fish"]
values = [[4,9,12],[6,3,8],[7,5,10],[2] ]

const output = keys.map((key, index) => {
  return {"name": key, "data": values[index]}
})

console.log(output)

Alternatively, you may want to reconsider using an object for easier access to key/value pairs:

keys = ["Dog", "Cat", "Rabbit", "Fish"]
values = [[4,9,12],[6,3,8],[7,5,10],[2] ]

const output = {}
for (let j=0; j<keys.length; j++) {
  output[keys[j]] = values[j]
}

console.log(output)

This data structure allows for quick retrieval of information using keywords like output.Dog. On the other hand, iterating through arrays would be necessary with the current format.

(Please note that searching for JSON methods was not relevant to your question as you are dealing with data transformation rather than JSON manipulation. JSON simply represents a data object in string form.)

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

Vue - Additional loading may be required to manage the output of these loaders

Currently working with Vue and babel. I have a function that's been exported // Inside file a.js export async function get() { ... } I am trying to link this exported function to a static method of MyClass // Inside file b.js import myInterface fr ...

Tips for preserving the jquery inputmask after updating the DOM

It's difficult to explain, but here is a snippet showcasing the issue. (function() { var PhoneNumber = function() { this.name = ko.observable(); this.phone = ko.observable(); }; $('[data-mask="phone"]').inputmask({ mask ...

AngularJS allows for editing elements in an array, but not string objects directly

I am a beginner in AngularJS, currently in the learning phase. Query I want to edit a specific rma from the list. When I click on the edit button and call the controller function updateRma(rma), after selecting rma number 11, my absolute URL is "http://l ...

Exploring the power of AJAX and JSON in a jQuery calendar within an ASP.NET environment

Currently, I am utilizing a jQuery calendar that employs Ajax with JSON to populate its events. My goal is to retrieve the JSON array from a C# function in ASP.net. However, despite my efforts, I haven't been successful in populating the calendar corr ...

The code in the head section is not running as expected

I've been exploring the possibilities of using lambda on AWS in combination with api gateway to create a contact form for a static S3 website, all inspired by this informative blog post: https://aws.amazon.com/blogs/architecture/create-dynamic-contact ...

Steps to resolve: Eliminate repeated entries within a JSON document and save the corrected data in a fresh file

I have a large JSON file with approximately 400,000 entries, each representing a city. My goal is to filter out cities that are not located in Germany and remove any duplicate cities. Once this is done, I need to save the filtered cities into a new JSON fi ...

Arranging cards in a stack using VueJS

I am currently working with a small vue snippet. Originally, I had v-for and v-if conditions in the snippet, but due to issues reading the array, it is now hardcoded. The current setup produces three cards stacked on top of each other. I am exploring opti ...

Looking for a skilled JavaScript expert to help create a script that will automatically redirect the page if the anchor is changed. Any t

Seeking a Javascript expert, In my custom templates, I have used a link as shown below: <a href='http://www.allbloggertricks.com'>Blogging Tips</a> I would like the page to redirect to example.com if the anchor text is changed from ...

Managing operations in Swift 2.0

I am currently working with Swift 2.0 on IOS 9.2.1 using Xcode 7.2. As I am learning Swift 2.0, I have developed a routine that involves creating a NSURL Session to retrieve JSON data and parsing it successfully. Everything is working as expected... Howe ...

Navigating between routes in NEXT JS involves passing state, which can be achieved through various

Within one of my page objects, I have some data that I need to send to another page when redirecting. The code snippet below shows how I achieved this: const redirectAppointmentStep1 = (value) => { router.push({ pathname: '/Appointment/bo ...

Choosing different elements using identical classes in JQuery

Struggling with a coding problem that seems like it should be an easy fix, but can't quite figure it out. The HTML code I have is as follows: <section class="actualite"> <div class="actualite-text"> <h3 class="title"&g ...

Invoke a Python function from C, sending float arrays as parameters and saving the resulting data into them

I'm currently developing an astronomy application that requires reading a CASA MS File in Python. This file is designed to be easy to read, but I also need to work with CUDA for processing. My goal is to save the data from the file as u,v coordinates ...

What is the best way to empty an array within the state of a React component using JSX?

I need assistance with a React and JSX project where I am creating input fields that can be removed by clicking a button. Currently, I have an empty array stored in the state of the Page component. This array is updated using the addItems function. Howev ...

Angular: Exploring the differences between $rootScope variable and event handling

I have a dilemma with an app that handles user logins. As is common in many apps, I need to alter the header once the user logs in. The main file (index.html) utilizes ng-include to incorporate the header.html I've come across two potential solution ...

What happens when you click and trigger mouseleave?

window.onload = function() { $(".compartir").hover(function() { console.log('hover'); var self = this; setTimeout($(self).addClass('ready'), 500); }, function() { var self = this; console.log('leave'); ...

Managing post requests in node.js using busboy and then multer

I'm currently facing an issue with busboy (or multiparty) and multer while trying to parse my request. Initially, the request is received successfully using busboy, where I proceed to create a folder and update my database. However, when I attempt to ...

Tips for implementing automatic line wrapping in a PDF document using React-PDF

I am experiencing an issue with a PDF rendering where very long words are not wrapping onto a new line, instead overflowing the container and disappearing off the page. Below is the setup causing this problem. The styles are listed followed by the actual ...

Creating an API definition in Swagger with multiple objects at varying levels: A step-by-step guide

I am currently working on creating an API in Swagger using YAML. My goal is to establish a global document definition that aligns with the following JSON structure: { "document_info" : { "name" : "string", "file" : "base64" }, "document_d ...

Encountering issues with Monaco Editor's autocomplete functionality in React

I'm facing an issue with implementing autocomplete in the Monaco Editor using a file called tf.d.ts that contains all the definitions in TypeScript. Despite several attempts, the autocomplete feature is not working as expected. import React, { useRef, ...

Transforming JSON data with jq and converting it to CSV format, merging two columns together into a single one

JSON file: This portion is taken from the JSON file: "RoleDetailList": [ { "AssumeRolePolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Action": ...