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

Create a modal using the base of a[href^=“#id”]

What is the best way to minimize a call modal window? $('#button-1').on('click', function() { $('#modal-1').addClass('j-modal--open'); }); $('#button-2').on('click', function() { $(' ...

What could be causing the failure of the update for this computed property in my Vue 3 application?

Currently, I am in the process of creating an audio player using Vue 3 and the Napster API. About the Project I have managed to make the vinyl rotate by utilizing a CSS keyframes-based animation paired with the computed property isSpinning. I intend for ...

Retrieve the key values from an object of a generic type

Is there a way to retrieve the keys of the object when it is of type T? I attempted to accomplish this using different methods such as: function getGenericTypeKeys<T>(): string[] { return Object.keys({} as T); } and function getGenericTypeKeys< ...

Altering the color of a div based on a specified value condition

I am in need of assistance with a div structure similar to this: <div id="namacoc" tabindex="1" class="filled-text" placeholder="Input your name" contenteditable ></div> <div id="position" tabindex="1" class="filled-text" placeholder="Input ...

What is the HTML code to display a table and a video/image side by side?

I'm facing a challenge while trying to create a website. I want to place a table in the center of the page, with videos on either side of it. However, whenever I attempt this, the table ends up below the videos instead of being aligned with them. I&ap ...

Ways to verify whether any of the variables exceed 0

Is there a more concise way in Typescript to check if any of the variables are greater than 0? How can I refactor the code below for elegance and brevity? checkIfNonZero():boolean{ const a=0; const b=1; const c=0; const d=0; // Instead of ma ...

What steps should I take to modify the API addresses within the React project build?

In my React project, I am looking for a method to dynamically change the API addresses after building it. Is there a way to accomplish this without using environment variables? I want to be able to modify the API address even after the build process is c ...

If the option is 'Gel', use an if statement to console log

I'm trying to console.log the option from the data() function that is equal to 'Gel'. I attempted to use an if statement, but it doesn't seem to be working. Anyone have any ideas on how to make this work? data(){ return { ...

How come my Bootstrap tooltip title only updates once when I use the keydown event in jQuery?

My goal is to provide users with a character count for text inputs and textareas based on a maximum limit. To achieve this, I have added tooltips to elements with a data-maxlength attribute. I update the tooltip for text inputs to display the current lengt ...

Launch a dialogue box by clicking on the buttons corresponding to the article ID

I am currently in the process of setting up an admin panel with some quick actions for managing my articles, such as deleting them. When I click on the trash can icon, a dialog box should open and prompt me to confirm the deletion. This dialog box should b ...

Automatically fill in checkboxes based on user input

Having a simple problem here, I am attempting to dynamically populate check-boxes in an HTML form. However, when I try using the checked property of the checkbox in HTML, it doesn't work correctly. The checkbox remains checked whether I use checked=&a ...

What is the best way to extract HTML using selenium.webdriver in Python?

Appreciate your attention, and please excuse any errors in my English. I am currently attempting to retrieve HTML from . The process involves entering some text into an input box and clicking a button, which triggers the following actions: Load the Yaho ...

Encountering the issue of "unexpected error: autocomplete is not defined" when trying to retrieve information

I am using jQuery for retrieving remote data but encountering an error Uncaught TypeError: $(...).autocomplete is not a function. I have made several attempts, yet I cannot identify the root cause of this issue. It seems like there might be an error in ...

If variable is greater than, hide the division element

I have a variable called lineNum that increases each time I click on an h1 element I'm attempting to use an 'if' statement to hide a div by setting its display to none, but for some reason, I can't seem to get the 'if' code r ...

Encountering issues with configuring an Express server with HTTPS

Having difficulty setting up my Express server on HTTPS and accessing my API. Below is the code I am using: // server.js const express = require('express'); const { readFileSync } = require('fs'); const https = require('https' ...

Adjust the divs right element by adding or removing 1 pixel for every size change in the browser

I have been exploring different approaches to achieve this task and it seems like using javascript might be the most effective way. I am currently dealing with a stubborn social icon container placement issue. More details on my previous question can be fo ...

Is there a method to retrieve all Class elements without using a for-loop?

I am trying to retrieve all elements with a specific class using document.getElementsByClassName(); <body> <div class="circle" id="red"></div> <div class="circle" id="blue"></div> <div class="circle" id="yell ...

Accessing Properties in React.js: A Guide

<Element id="1" onClick={this.runFunction(???)}/> When the onClick event is triggered, I want to execute a different function with the key value "1" as an argument. How can I make this happen? Thank you. ...

The development chrome extension failed to load due to an invalid port or malformed URL pattern

I'm encountering an issue while trying to load my development chrome extension for debugging. The error message I am receiving is: Issue with 'content_scripts[0].matches[0]' value: Path cannot be empty. Manifest failed to load. This is th ...

Utilizing express.js to access an HTML document

var express = require("express"); var fs = require('fs'); var sys = require('sys'); var app = express(); app.use(express.logger()); app.get('/', function(req, res){ fs.readFile('/views/index.html'); }); ap ...