Is it possible to convert an object with properties of equal length into a list of objects using JavaScript?

I am working with an object that has multiple keys, each containing a list of equal length:

myobj = {
    'key1' : [1, 2, 3],
    'key2' : ['a', 'b', 'c'],
    'key3' : [true, false, true],
    ...,
    'keyN' : ['length', 'of', 'three'],
}

To achieve my goal, I need to restructure this object into a list of "smaller" objects. Each object in the final list will contain the respective values from each initial list at the same index position. Here's how the transformed object would look based on the example provided:

[
    {
        'key1' : 1,
        'key2' : 'a',
        'key3' : true,
        ...,
        'keyN' : 'length'
    },
    {
        'key1' : 2,
        'key2' : 'b',
        'key3' : false,
        ...,
        'keyN' : 'of'
    },
    {
        'key1' : 3,
        'key2' : 'c',
        'key3' : true,
        ...,
        'keyN' : 'three'
    }
]

Answer №1

It's unclear what troubleshooting steps you've taken so far. You may want to consider attempting the following suggestions.

var a = {'fruit' : ['apple', 'banana', 'orange'],
    'color' : ['red', 'blue', 'green'],
    'status' : [true, false, true]}

var result = []

Object.keys(a).map(key => {
  a[key].forEach((item, index) =>  result[index] ? result[index][key] = item :      result[index] = {[key]: item})
  }
 )
 
 console.log(result)

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

Sending PHP variable to xmlhttp.responseText

I haven't come across this specific situation before, so I thought I would ask for help. My JavaScript code is using AJAX to call a PHP file, run the script in it, and then return a concatenated PHP variable via xmlhttp.responseText to alert that resp ...

jQuery Ajax allows scripts to be contained within a page, even if the page itself is empty

Utilizing jQuery ajax to display an HTML page that includes javascript functions, here is my code: function ChartBook() { $.ajax({ url: '/Charts/ChartBook', dataType: 'html', id: 1, ...

What should I do to resolve the issue of the function if ($(window).width() < 768) {} not functioning properly upon resizing the browser?

I am working on a functionality where the navigation bar items will toggle hidden or shown only when the browser width is less than 768px and an element with the class "navlogo" is clicked. I have included my code below for reference. if ($(window).width( ...

Tips for creating a responsive tab indicator in Material UI?

I successfully integrated react router with material-ui and the routing system is working as expected. Clicking on a tab routes you to the corresponding component. However, I am facing an issue where the blue underline indicator that typically accompanies ...

What is the best way to maintain a Tampermonkey script within Selenium?

I'm trying to execute a JavaScript script before the page loads, so I've placed it in Tampermonkey. However, the script doesn't persist after closing the driver. Whenever I run the code again, the saved script is no longer there. This code u ...

Node.js and Express: Delivering Seamless Video Streaming via HTTP 206 Partial Content

Having a binary file like an mp4 video in a MarkLogic database, I am utilizing the Node.js API of the database to stream this document in segments. The structure is as follows: html document <video controls="controls" width="600"> <source src= ...

Trying to access a property that doesn't exist (fetching 'fetchBans')

My goal is to create a command within my Discord bot that can unban a user. However, when I finished writing the code, I encountered an error stating 'Cannot read properties of undefined (reading 'fetchBans'). Here is the section of code cau ...

Guide on extracting information from a JSON array consisting of objects and adding it to a Pandas Dataframe

Working with Jupyter Notebook and handling a Batch API call that returns a JSON array of objects can be tricky. The parsing process involves using for loops, which may seem weird at first. In my case, I needed to extract specific JSON object information an ...

AngularJS fails to display JSON data

I've been experimenting with AngularJS by creating a basic gallery that pulls images from a JSON file, but for some reason I'm having trouble displaying the data. index.html: <!DOCTYPE html> <html ng-app="portfolioApp"> <head> ...

Is it possible to combine the existing request parameters with a new parameter in JSP/JSTL/JQuery?

Here is a sample URL: http://127.0.0.1:8080/admin/seller?email=tim%40example.com Below is a snippet of JSP code: <a class="btn btn-primary ${page==pages||pages==0?'disabled':''}" href="?page=${page + 1}">Next</a> I am ...

Unexpected state being returned by Vuex

I am encountering an issue with a pop-up modal that is not behaving as expected. The condition for the pop-up to appear is if the user has no transactions, which is determined by checking the length of the depositHistory array. If the length is greater tha ...

What is the process for redirecting to an external URL while including post parameters?

When a user accesses my endpoint, I need it to automatically redirect them to an external URL with URL-encoded form parameters. Endpoint: https://example.com Form Parameters: Name: testing ID: 123456 I have attempted the following in Express. It succes ...

a guide to transforming data into a string with json using angular

I am struggling to figure out how to bind my form data into a JSON string. My situation involves using a string field in the database and saving checkbox values in a single database column using JSON. I have created an HTML form, but I am unsure of how to ...

Creating a Vue.js vuetify input that restricts the user to entering only three digits before the decimal point and two digits after the decimal point

I am looking to implement a restriction on the total number of input digits to 3. Users should be able to enter numbers like 333, 123, etc. However, if they include a decimal point, they should only be allowed to enter 2 digits after the decimal point. Val ...

Why does JSON.parse() in my AJAX response return undefined?

I've been developing a small app that sends an AJAX GET request to a URL, which responds with JSON using the PHP `json_encode()` function. However, when I attempt to access individual values from the JSON response, it indicates undefined. Surprisingly ...

Caution: The `className` property does not align with Material UI css which may cause issues upon reload

https://i.stack.imgur.com/MxAiY.png If you are facing the error/missing CSS, check out this video for a visual representation. While older versions of similar questions exist on Stack Overflow such as React + Material-UI - Warning: Prop className did not ...

Does Objective C have a counterpart to the encode() method in JavaScript?

NSString *searchString = @"Lyngbø"; NSLog("%@",[searchString stringByAddingPercentEscapeUsingEncoding:NSUTF8StringEncoding]); The result is: Lyng%C3%B8 <script type="text/javascript"> document.write(escape("Lyngbø")); </script> The result ...

What is the best way to iterate through elements that come after a specific element?

I'm confident that I will be able to provide an answer to this very soon... Here's a sample code snippet: <script> function ClearAndRunFuncs(element) { //Clears responses for elements AFTER this element with an onchange //Executes the uni ...

`Generating a JSON object with varying values for a shared key`

Here is the array I have: [{"option":"27 : 28","image":""},{"option":"20 : 25","image":""},{"option":"28 : 27 ","image":""},{"option":"25 : 20","image":""}] I need to display these four options using PHP, how can I do that? The expected output should be ...

Ending a timer from a different function in a React component

Currently, I am delving into the world of React and attempting to create a timer component. While I have successfully implemented the start function for my timer, I am now faced with the challenge of stopping the timer using an onclick handler from another ...