What is the best way to combine two arrays into an object with assigned names for values?

Here are the two arrays I am working with:

const values = ['Master Clean', '45', '650']
const names = ['servicemenus.$.name', 'servicemenus.$.duration', 'servicemenus.$.cost']

The desired output should look like this:

{ 'servicemenus.$.name':'Master Clean',  'servicemenus.$.duration': '45', 'servicemenus.$.cost': 650}

Answer №1

It is essential to ensure that these two Arrays always maintain the same length. Here is a for loop that can assist you in achieving this:

const values = ['Master Clean', '45', '650']
const names = ['servicemenus.$.name', 'servicemenus.$.duration', 'servicemenus.$.cost']
var obj = {}
for (var i = 0; i < names.length; i++) {
  //you could also use: if (values.length > i) { assignment }
  obj[names[i]] = values[i];
}
console.log(obj);

The resulting output will be:

Object { servicemenus.$.name: "Master Clean", servicemenus.$.duration: "45", servicemenus.$.cost: "650" }

Additionally, if you require further assistance, you may find the following question helpful: Merge two arrays into one Json object

Answer №2

To manipulate the array's index while using a forEach loop, you can create dynamic object keys by referencing each other:

const values = ['Master Clean', '45', '650']
const names = ['servicemenus.$.name', 'servicemenus.$.duration', 'servicemenus.$.cost']

let updatedData = { };

names.forEach( (name,index) => {
  updatedData[name] = values[index];
});

This approach produces the desired outcome.

Answer №3

Assuming that both arrays are of equal length, we can take one of them as a reference point and iterate through it to create an object:

let obj = {};
keys.forEach((key, index) => {
    obj[key] = data[index];
});

console.log(obj);

Answer №4

When working with arrays in JavaScript, you have the option to use the reduce method to consolidate elements into a single value, such as an object. This can be achieved by providing the reduce function with an accumulator, current value, and index parameter to reference values from another array. The Object.assign method is then used to create an object containing the desired keys and corresponding values.

const data = ['Title', 'Author', 'Pages'];
const labels = ['book.$.title', 'book.$.author', 'book.$.pages'];

const result = labels.reduce((acc, current, index) => Object.assign(acc, {[current]: data[index]}), {});

console.log(result)

Answer №5

Iterate through the properties of an object using a for-in loop and create a new object

var newObj = {};
for(var key in originalObj) {
  newObj[key] = originalObj[key];
}
console.log(newObj);

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

Stopping default actions is effective on Firefox but not Chrome

When you click on this link <a id="c2c" href="#" class='test' style="margin-left:300px;"><img src="img.png" height="400" width="480" alt="Click Here"></a> This is the code I have written $('#c2c').click(functio ...

Display a confirmation message upon successful validation of a form using Bootstrap 4

After trying to implement a success modal that shows up upon successful form validation using Bootstrap 4 and its JavaScript code, I made a slight modification. However, I am uncertain if this is the correct approach to handle it. I believe there might be ...

Preventing click event from bubbling up the DOM: Using Vue's @click

How can I access the child elements within a parent component? <div v-on:click.stop.prevent="onClickTemplateHandler"> <div> <h3 style="">Title</h3> <p>{{ lorem }}</p> </div> ...

Transmitting a vast amount of data through a single stream using NodeJS and ExpressJS

I am currently in the process of creating a prototype for an application using the native mongo rest api. In this scenario, Node returns approximately 400K of JSON data. To make the request to mongo's native API and retrieve the result, I am using the ...

Using Javascript's Array.reduce() function causes the page to crash with Error Code 6

Everything runs smoothly on the webpage unless I provide an initial value, causing a TypeError due to only one remaining element (as expected). In an attempt to fix this, I decided to pass 0 as the initial value for the reduce function (line 4 in the code ...

Creating PDFs in iOS and Android using Ionic framework

Seeking assistance with resolving this issue. I have researched extensively on Google, jspdf, pdfmake.org, inappbrowser plugins, but have been unsuccessful in getting my Ionic project to function properly. The goal is to create a simple form that includes ...

Exploring Methods to Iterate through an Object Utilizing Two Arrays

Attempting to iterate through states passed as props in another component state = { question:[firstQ, secondQ, thirdQ], tag:[[1,2,3],[4,6],[a,b,c,d]] } I aim to display it on the next Componet with a pattern like: FirstQ [tag1] SecondQ ...

Switching the default z-index for child elements within an HTML container

According to the specification, elements are typically drawn "in tree order" for in-flow, non-positioned elements of similar block level or float status and identical z-index. This means that elements declared last in the HTML markup appear on top. But wha ...

"Phraseapp is in the process of refreshing the primary language document

I currently have a locale file that contains various text keys that need to be translated. Each key corresponds to a specific text that needs to be translated into different languages: { key1: "Text to translate", key2: "Another text to translate", ...

Output values in JSON array are not displaying

I've been struggling with my code and have searched extensively for solutions to no avail. The issue I'm facing is that the output is completely blank, despite double and triple-checking all the necessary variables like host, user, pass, dbname, ...

Learn how to retrieve data from a JSON server in Angular 8 and then sort that data in a table by utilizing checkboxes

Currently, I'm in the middle of an Angular project where I could use some assistance on how to filter data through checkboxes within a table. The setup involves a home component that displays data from a JSON server in a tabular format using a service ...

Why is the parent element not receiving the event in Vue.JS? Is it necessary for the parent to be a custom component in order to receive the

I'm new to Vue.js. I used to think that Events worked by bubbling up through the DOM tree until caught by a parent element. However, something seems to be off. The code below isn't functioning as expected - there are no errors or warnings, and in ...

How can we best organize a VueJS application to accommodate this specific logic?

I am currently working on an app that needs to display data fetched from multiple sources based on a condition. The issue I am facing is that the process of fetching, organizing, and returning the data varies depending on the source, sometimes even requiri ...

Massive HTML Table Containing Rows upon Rows

Currently, I have a server that can provide me with a list of objects in json format, and my goal is to showcase them in a table on the client side. Initially, I thought about dynamically modifying the DOM after receiving data from the server. Building th ...

Three.js: Apply a single color to a mesh shaderMaterial until a specific point is reached

I am struggling to grasp the concept of Three.js shaders. My goal is to apply a color to a mesh, but only up to a specific point. Here is my progress so far. I want the green color to "stop" at 50% of the mesh height For the remaining part of the mesh (ab ...

Ensuring the child div's height does not overflow beyond the parent div

When dealing with a parent div and a child div, both having different heights, how can I specifically retrieve the height of the portion of the child div that is within the boundaries of the parent div? Using document.getElementById("id").style.height prov ...

PHP does not recognize a POST request from AJAX originating from the same page

Hey everyone, I'm having some issues with my code and I've tried everything to fix it without success: <?php if(isset($_POST['sInput'])){ $sInput=($_POST['sInput']); echo "$sInput"; }else{ echo ...

Attempting to utilize the Optimist API's help() function to display the usage() information

I am relatively new to using optimist and despite my attempts at researching and experimenting, I have been unable to find a streamlined method for incorporating a --help option. In the documentation, there is mention of a help() function. Based on this i ...

Problems with spacing in Slick slider and lazyYT integration

Utilizing lazyYT helps to enhance the loading speed of YouTube videos. Once loaded, these lazyYT videos are then placed within a slick slider. However, an issue arises where the videos stick together without any margin between them. To address this problem ...

Extract data from ajax and send it to php

Struggling to retrieve the value from a dropdown menu and pass it to a PHP variable when the selection changes in an HTML form. Additionally, looking to dynamically update the options in a second dropdown based on the selection in the first one. Any help w ...