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

The specified object '[object Object]' is not compatible with NgFor, which only supports binding to iterable data types like Arrays

I have some code that is attempting to access objects within objects in a template. <table class="table table-striped"> <tr *ngFor="let response of response"> <td><b>ID</b><br>{{ response.us ...

The system encountered an error when attempting to convert the data '19-10-2002' into a date format

I am trying to pass a date parameter in the format (dd-MM-yyyy) and then convert it into the format (yyyy-MM-dd) before sending it via API. Here is my code: convert(date:string){ date //is in the format(dd-MM-yyyy) date = formatDate(date , " ...

AngularJS: Issues with data retrieval in parallel in $http get requests within a $.each loop

Attempting to fetch data for multiple IDs is the goal: (Simplified version, aiming to clarify) Controller: var idList = [39,40,41]; $.each(idList, function(key, value){ var dataObject = { type: "test", id: value }; var getData = DataFactor ...

Use regular expressions and JavaScript to enclose a series of English letters within a wrapper

I am looking to enclose a series or cluster of consecutive English characters within a <span> tag. In simpler terms, I aim to alter the appearance of English language in my writing. Therefore, I need to identify English characters and surround them ...

TensorflowJS Error: The property 'fetch' cannot be read as it is undefined

I am working on an Angular 7 application and attempting to load the mobilenet model by following the instructions in this example. To do this, I first installed tensorflowjs using the command npm install @tensorflow/tfjs (based on the steps provided in th ...

Emphasize rows in the MUI-Datatables framework

A table was created using React.js and MUI-Datatables: import MUIDataTable from "mui-datatables"; const columns = ["Name", "Company", "City", "State"]; const data = [ ["Joe James", "Test Corp", "Yonkers", "NY"], ["John Walsh", "Test Corp", "Hartford", ...

JavaScript isn't functioning properly after UserControl is loaded via Ajax

Thank you, Stilgar for helping me solve my issue. I created a javascript file and placed all my code in it. After adding this file to the UserControl and retrieving the UserControl's html, I used $("#DivID").html(UserControlHTML). Now everything is wo ...

How can I retrieve data from local storage based on a specific key value using a query?

In order to optimize the storage of data for my app, I have successfully stored a large amount in local storage. Now, I am faced with the task of fetching data in an array but only selecting key/values that are specifically chosen, rather than all or jus ...

Utilizing ngModel within the controller of a custom directive in Angular, instead of the link function

Is there a way to require and use ngModel inside the controller of a custom Angular directive without using the link function? I have seen examples that use the link function, but I want to know if it's possible to access ngModel inside the directive ...

The undefined dispatch function issue occurs when trying to pass parameters from a child component to React

There is an action that needs to be handled. It involves saving a new task with its name and description through an API call. export const saveNewTask = (taskName, taskDescription) => async dispatch => { console.log(taskName, taskDescription); c ...

Issue encountered when attempting to generate a mongoose schema using a JSON document

Can I define this JSON file structure as a mongoose schema? Mongoose lacks an object type, and I'm unsure how to proceed with it. { "Moutainbike": { "Cross": { "size": [ "395 mm", "440 mm", "480 mm", "535 mm" ], "color" ...

Transform geojson data into an HTML table

As someone new to JavaScript, I am trying to figure out how to populate a HTML table with geojson entries like "ename" etc. Here is my current code: <table id="jsoncontent"></table> <script type="text/javascript"> window.onload = fu ...

What are the benefits of keeping JavaScript and HTML separate in web development?

Recently, I came across the concept of Unobtrusive JavaScript while researching best practices in the realm of JavaScript. One particular point that grabbed my attention was the idea of separating functionality (the "behavior layer") from a web page's ...

How to retrieve properties of the final item in an array using Vue.js

Struggling with Vue.js JavaScript implementation. This is the current code: <div id="app"> <h1>Items</h1> <div v-for="item in items"> <input v-model="item.val"> </div> <button @click="addItem"> Ne ...

Leveraging the powerful SQLite JSON functions, my intention is to fetch a specific value by considering the neighboring values

Suppose I have a JSON structure and I want to extract the age values associated with the name "Chris" in the Array key. { "Array": [ { "age": "65", "name": "Chris" ...

Guide on converting nested arrays into a hash or JSON with arrays as values

I am faced with a nested array problem array = [["Colorado", "Adams County"], ["Colorado", "Jefferson County"], ["California", "Amador"], ["California", "Tulare"]] My desired outcome should look like this {"Colorado" => ["Adams County", "Jefferson Co ...

Generate a folder structure based on the Delta data provided by the Dropbox API utilizing the file paths

I came across a query on how to convert a file path into a treeview, and I'm uncertain about achieving the desired outcome using JavaScript: My goal is to transform an array of paths into a JSON tree structure: var paths = [ "/org/openbm ...

Enhance your React application by using a personalized hook that allows you to trigger a function

After creating a custom hook to handle uploads to an AWS S3 bucket, I encountered a small issue. Rather than having the hook execute the logic directly, I decided to create an executable function to return instead. However, I am facing a problem where the ...

The dilemma between installing Electron or installing Electron-Builder: which one

When it comes to installing Electron for an Electron app with React, the method can vary depending on the tutorial. Some tutorials use electron-builder while others do not, but there is little explanation as to why. First: npx create-react-app app cd app ...

AngularJS UI-Router: Utilizing Optional Parameters

.state('registration', { url:'/app/registration/:ref', templateUrl: 'partials/registration.html', }) This is my configuration for routing using ui-route. It functions properly when I go to localhost:80/r ...