How to convert an array of keys and an array of values into an array of objects using JavaScript

My question is similar to the one found here: Merging keys array and values array into an object using JavaScript

However, I am unable to find a solution for my specific scenario. If I have these two arrays:

const keys = ['x', 'y', 'z'];

const values = [
  [0, 1, 2],
  [10, 20, 30],
];

How can I merge them into an array of objects to achieve the desired output?

[
  {
    x: 0,
    y: 1,
    z: 2,
  },
  {
    x: 10,
    y: 20,
    z: 30,
  },
]

Answer №1

To achieve this, you can utilize the Array.prototype.map() and Array.prototype.reduce() methods:

const keys = ['a', 'b', 'c'];

const values = [
  [100, 200, 300],
  [400, 500, 600],
];

const result = values.map(array => array.reduce((accumulator, currentValue, index) => {
  accumulator[keys[index]] = currentValue;

  return accumulator;
}, {a: null, b: null, c: null}));

console.log(result);

Alternatively, you can achieve the same without using reduce() like this:

const result = values.map(array => ({
  [keys[0]]: array[0],
  [keys[1]]: array[1],
  [keys[2]]: array[2]
}));

Answer №2

Iterate through the arrays of values and create an object for each one. Then, go through the individual values within those arrays and use another array as the keys.

const keys = ['x', 'y', 'z'];

const values = [
  [0, 1, 2],
  [10, 20, 30],
];

const output = [];
values.forEach((v, i) => {
  output[i] = {}; // generate objects for each value array
  v.forEach((w, j) => {
    output[i][keys[j]] = w; // assign values to the corresponding keys
  });
});

console.log(output);

As mentioned in comments, this process can also be achieved using Array.reduce:

const keys = ['x', 'y', 'z'];

const values = [
  [0, 1, 2],
  [10, 20, 30],
];

const output = values.map(x => { // iterate over each values array
  return x.reduce((a, c, i) => { // take each value
    a[keys[i]] = c // map it to an object property iteratively
    return a; // combine them into a single object.
  }, {});
});

console.log(output);

Answer №3

const properties = ['length', 'width', 'height'];

const dimensions = [
  [10, 20, 30],
  [5, 15, 25],
];


function createObject(properties, dimensions) {
    let objectArray = []
     for (let i = 0; i < dimensions.length; i++){
         let newObj = {};
         for(let j=0;j<properties.length;j++){
             newObj[properties[j]] = dimensions[i][j];
            
         }
        objectArray.push(newObj)
     }
    return objectArray 
    console.log(objectArray)
     
 }
 
 createObject(properties,dimensions )

testing out some code!

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

Error encountered in Google's Structured Data Testing Tool

<script type="application/ld+json"> {"@context" : "http://schema.org", "@type" : "LocalBusiness", "name" : "mywebsite.com", "description": "Lorem ipsum dolor sit amet", "image" : "http://mywebsite.com/image.jpg", "telephone" : "987654321", ...

What's the issue with my jQuery AJAX script?

I am experiencing an issue with my ajax pages using jQuery to retrieve content. Only one page seems to be working properly, even though I have multiple pages set up. How can I resolve this problem? $(document).ready(function() { $('.lazy_content& ...

Is it possible to dynamically alter a CSS property using styled components when an onClick event occurs?

Hey there, I'm pretty new to React and currently exploring styled components for the CSS styling of my components. One of the components I've created is a button called SummonButton: const SummonButton = styled.button` height: 50px; borde ...

Arrange the Proxy Array of Objects, the localeCompare function is not available

Encountering an error while attempting to implement ES6 arrayObj.sort(a,b) => a.property.localeCompare(b.property) syntax: Getting TypeError: a.property.localeCompare is not a function. Suspecting that localeCompare might not be in scope, but unsure ...

Adding a version number to the splash screen in Cordova: A step-by-step guide

After successfully integrating the Cordova Splashscreen plugin into my Ionic project, everything is running smoothly. However, I am now looking to dynamically add a version number to the splash screen without manually editing the Splash Screen PNG file e ...

What is the best way to assign a variable with the type (x:number)=>{y:number,z:number}?

I am trying to initialize a variable called foo, but my current code is not compiling successfully. let foo: (x: number) => {y:number,z: number} = (x) => {x+1, x+2}; This results in the following error: Left side of comma operator is unused and ha ...

Employing square bracket notation based on the input data

I'm currently in the process of enhancing some code within my library, but I've encountered a perplexing issue with bracket notation not functioning as expected when attempting to call an imported class. The parameter type expects a camelCased s ...

Tips for accessing a variable through request.query

When I made a call to getContents() in my client-side code: $.getJSon("/getContents", function(room){ theRoom=$("#roomName").val();//textarea's value ... }); I am now trying to figure out how to retrieve theRoom variable in getContents(), which is ...

Tips for preserving HTML tags in responses within React Native applications

How can I preserve HTML tags in the response when using React Native? Here is an example of a response from Postman: { "enable": true, "faq": [ { "answer": "<ol>some text</ol>" ...

The React task list updates the todo items on change, rather than on submission

As a newcomer to React, I have embarked on the classic journey of building a todo app to learn the ropes. Everything seems to be functioning smoothly except for one minor hiccup: When I input a new todo and hit "submit", it does get added to my array but d ...

Sending back JSON arrays containing Date data types for Google Charts

One of my challenges involves using a 'Timelines' chart from Google Charts, which requires a JavaScript Date type when populating data. Here is my initial code snippet: var container = document.getElementById('divChart1'); var chart = ...

Having difficulty implementing dynamic contentEditable for inline editing in Angular 2+

Here I am facing an issue. Below is my JSON data: data = [{ 'id':1,'name': 'mr.x', },{ 'id':2,'name': 'mr.y', },{ 'id':3,'name': 'mr.z', },{ & ...

don't forget about the vertical multilevel navigation in the menu state

I've been working on creating a vertical multilevel navigation menu, but I'm having trouble figuring out how to make the last menu state stay active when switching to a new page. I've explored options like using hash locations and cookies, ...

Artwork expanding incorrectly on HTML canvas

I'm encountering an issue while attempting to draw on an HTML canvas. I've specified 50 circles and multiple lines within a canvas of size 1000x1000 px, but not all circles are appearing as expected. My assumption is that the elements are being ...

What are the steps to store and access state variables using session storage in a React application?

I am currently utilizing React version 18.2.0. In my application, I have a component called BodyComponent that stores the data retrieved from an API call in its state as results, along with some filter information in filters. The BodyComponent fetches the ...

Is there a way to verify if an ID includes more than one word?

I am trying to target a specific div with a unique id in jQuery: <div id="picture_contents_12356_title"></div> The '12356' is autogenerated and must be included in the id. I need to create a jQuery selector that combines "picture_co ...

Issues with Await and Async functionality in Angular and Ionic 4 causing unexpected behavior

Struggling to show error messages during the sign-up process? Constantly encountering the same issue in your code? The error TS1308 is throwing you off: 'await' expression is only allowed within an async function. Take a look at this problemati ...

Merge information from various sources using ajax

Currently, I have a single ajax request that retrieves data from an API and uses it to generate a table. Now, I'm looking to modify the code so that it can retrieve data from two different URLs and merge them into the same table (retTable). Below is ...

Unable to display AdaptiveCard Json as a BotFramework Message using C# code

I am attempting to incorporate an Adaptive Card json into a message that will be sent to the Bot Framework Channel Emulator. However, I am encountering an issue where the emulator displays the message "Can't render card". The Adaptive Card sample I a ...

This function is functional with jquery version 1.4.2 but encounters issues with jquery version 1.9.1

I have encountered an issue with a script that submits data to my database. The script worked perfectly on version 1.4.2, but the template I am using now requires version 1.9.1, so I updated my site accordingly. However, after the update, I am facing an er ...