Convert an array into individual objects and include key-value pairs from a separate object

I am working with two arrays that have the same length:

One is a simple array

numbers = [4,5,6]
  

The other is an array of objects

objects = [
    {type: "x", value: 7},
    {type: "y", value: 8},
    {type: "z", value: 9}
  ]
  

My goal is to combine these two arrays into a new array. I want to take the values from the first array and assign them keys as 'item', while combining all the types as shown below:

result = [
   {item: 4, type: "x"},
   {item: 5, type: "y"},
   {item: 6, type: "z"},
  ] 
  

Answer №1

arr2 = [
  {dog: "x", other: 5},
  {dog: "y", other: 10},
  {dog: "z", other: 15}
];
arr1 = [7,8,9];

let result = [];
for (let j=0; j<arr1.length; j++) {
    result.push({node: arr1[j], dog: arr2[j].dog});
}

console.log(result);

Answer №2

If you iterate through arr1 and simultaneously create new objects based on the elements of arr2, you can merge them together

    arr1.map((value, idx) => ({ ...arr2[idx], node: value }))

To only extract the 'cat' property from arr2 while iterating through arr1, use this:

    arr1.map((value, idx) => ({ cat: arr2[idx].cat, node: value }))

arr1 = [1,2,3];

arr2 = [
  {cat: "a", other: 0},
  {cat: "b", other: 0},
  {cat: "c", other: 0}
];

end = arr1.map((value, idx) => ({ cat: arr2[idx].cat, node: value }));

console.log(end)

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

Having trouble converting a JSON array into a JavaScript array upon creation

I have encountered this question multiple times before and despite trying various solutions, I have not been able to find success. Summary: My goal is to retrieve the array from the classes.json file and then assign the data in the variable classes from d ...

Store the text area content as a JSON object

What is the best way to store the content of a textarea in JSON format? I am currently working on a project where I have a textarea element and I need to save its value into a JavaScript object. Everything is functioning correctly except when 'enter ...

Reload the MEN stack webpage without the need to reload the entire page

I am in the process of developing a data analytics dashboard using the MEN stack (MongoDB, Express.js, Node.js). I have successfully implemented functionality to display real-time data that refreshes every 5 seconds without the need to reload the entire ...

What is the best way to reset a dropdown list value in angular?

Is there a way to erase the selected value from an Angular dropdown list using either an x button or a clear button? Thank you. Code <div fxFlex fxLayout="row" formGroupName="people"> <mat-form-field appearance=&quo ...

Encountering issues with link functionality on homepage due to React-Router v6 and Material-UI Tab integration

I'm currently working on a homepage that requires different page links. Below you can find the necessary code snippet for setting up the tabs and routes for each page: <li> The tabs are located here - <Link to="/demo">D ...

Angular 4 encounters a hiccup when a mistake in the XHR request brings a halt to a

In my Angular 4 application, I have implemented an observable that monitors an input field. When it detects a URL being entered, it triggers a service to make an XHR request. Observable.fromEvent(this._elementRef.nativeElement, 'input') .debou ...

Tips for preventing redirection in Vue 3 composition API with asynchronous requests

I have successfully configured a submission form to send data to my email and add it to a Google sheet using the method described in this GitHub link. The process worked seamlessly for both purposes. However, I am facing an issue where upon submitting the ...

The click event triggered by the onclick clone/function may not always activate the click handler

As a newcomer in the JavaScript domain, I am encountering an issue where the first clone created after clicking 'add more' does not trigger my click me function. However, every subsequent clone works perfectly fine with it. What could be causing ...

Building a matrix-esque table using d3.js reminiscent of HTML tables

I would like to generate a table resembling a matrix without numerical values. 1. Here is an example of my database table: | CODE | STIL | SUBSTIL | PRODUS | |------|-------|----------|---------| | R | stil1 | substil1 | produs1 | | R | stil1 | s ...

Continue to run upon clicking the button in the Document Object Model

I want the code to constantly change instead of executing only once. By default, the button has a dark mode for text and the background color is pink. When you click the button, the background color changes to black and the text in the button turns into li ...

Displaying Hierarchical Data with AngularJS and ng-repeat

Recently, I've been working on finding an elegant solution to represent hierarchical data in my application. Specifically, I have implemented a slide effect for bootstrap badges that showcase sub-categories using AngularJS. With some guidance from th ...

Select Menu (Code Languages:CSS, JS, HTML, BBCode)

I'm currently in the process of setting up a BB code for a forum I moderate. Here's the code snippet I'm using to generate a dropdown box that users can add to the signature field of their profiles: <!DOCTYPE html> <html> <d ...

What is the process for editing a JSON file and preserving the modifications?

I have a JSON file with a key (food_image) and I am looking to dynamically assign the index value in a loop to it, such as food_image0, food_image1 ... food_image{loop index}. After that, I aim to save this modified JSON file under a new name. All values ...

Executing a function to erase the stored value in local storage during an Angular unit test

Looking to verify whether the localStorage gets cleared when I execute my function. Component ngOnInit() { // Logging out when reaching login screen for login purposes this.authService.logout(); } authService logout() { // Removing logged i ...

Looking for a JavaScript code to create a text link that says "submit"?

Here is the code I have, where I want to utilize a hyperlink to submit my form: <form name="form_signup" id="form_signup" method="post" action="/" enctype="multipart/form-data"> ... <input type="submit" value="Go to Step 2" name="completed" /> ...

Is it possible for me to display dynamic content and utilize a template engine like (ejs)?

Currently, I am in the process of developing a weather application to enhance my skills with express and ejs. At the moment, I'm utilizing app.get to fetch data from darkSky's API successfully, and I can display it on my index.ejs page. My next ...

React Higher Order Components (HOCs) are functioning correctly with certain components but not

I have encountered an issue where using a Higher Order Component (HOC) to bind an action to various types of elements, including SVG cells, results in unintended behavior. When I bind the onClick event handler normally, everything works fine, but when I ap ...

Tips on deleting CSS comments from a CSS file

Currently, I am utilizing nextjs + reactjs. My objective is to eliminate all CSS comments from my existing css file. Despite using next-purgecss in order to get rid of unnecessary CSS code, the comments are still persisting. What could be the reason behind ...

Update the positioning of the element to center instead of the default top left origin using jQuery

I am facing an issue with positioning a marker inside a triangle, which is represented by a simple div, as shown in the image below: https://i.stack.imgur.com/0Q7Lm.png The marker needs to be placed exactly at the centroid of the triangle. However, it see ...

Detecting Scroll on Window for Specific Element using Jquery

I need help troubleshooting my code. I am trying to activate only one item that comes from the bottom of the page, but instead all div elements are getting activated. $(window).scroll(function() { $('.parallax').each(function(e) { if($( ...