Leverage the values of object properties from a pair of JavaScript arrays containing objects

I am working with two arrays

let arr1 = [{'id': 'ee', 'seat': '12'}, 
  {'id': 'aa', 'seat': '8'}
]
let arr2 = [
  {'id': 's22', 'num': ''}, 
  {'id': '2s2', 'num': ''}
]

My goal is to transfer the seat values from arr1 to the num property in arr2. However, I am encountering an issue where only the last seat value from arr1 is assigned in the for loop.

for( let i = 0; i <= arr1.length; i++) {
  for( let x = 0; x <= arr2.length; x++) {
    arr2[x]['num'] = arr1[i]['seat'];
  }
}

console.log(arr2);

Answer №1

Loop through arr2 using Array.forEach(), and assign the corresponding seat value from arr1 based on the index:

const arr1 = [{'id': 'ee', 'seat': '12'},{'id': 'aa', 'seat': '8'}]
const arr2 = [{'id': 's22', 'num': ''},{'id': '2s2', 'num': ''}]

arr2.forEach((o, i) => o.num = arr1[i].seat)

console.log(arr2)

Answer №2

To solve this problem, all you need is a single loop to iterate through the arrays and check if the index is smaller than the length of the smallest array.

If the index exceeds the length of an array, you will get an undefined access error since that element is not present in the array.

Attempting to access a property of this undefined element will result in the following error:

Unable to get property 'seat' of undefined or null reference

var arr1 = [{ id: 'ee', seat: '12' }, { id: 'aa', seat: '8' }],
    arr2 = [{ id: 's22', num: '' }, { id: '2s2', num: '' }],
    i, l;

for (i = 0, l = Math.min(arr1.length, arr2.length); i < l; i++) {
    arr2[i].num = arr1[i].seat;
}

console.log(arr2);

Answer №3

All you need is a single for loop to accomplish this task.

for(let index = 0; index < array1.length; index++) {
    array2[index].number = array1[index].position;
}

I trust this information will be useful to you!

Answer №4

To match indices and retrieve the desired data, this implementation should suffice.

const arr1 = [
  {'id': 'ee', 'seat': '12'}, 
  {'id': 'aa', 'seat': '8'}
]
const arr2 = [
  {'id': 's22', 'num': ''}, 
  {'id': '2s2', 'num': ''}
]

const result = arr2.map((e, i) => ({...e, ...{num: arr1[i].seat}}))

console.log(result)

If the goal is to include all seat values into num for each item, it can be achieved with minor adjustments.

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

Using Java for loops to group blocks into 8x8 arrays

I'm currently working on grouping 8x8 blocks of pixel data that I am retrieving from a BufferedImage. jpegPixels is a 3D integer array with height, width, and RGB size (0=Red, 1=Green, 2=Blue). pixelMatrix is a 2D integer array with a block size of ...

Vitejs is currently loading the entire bundle size instead of just the specific selected files

While working with Vue 3 and Vite, I came across an issue that seems quite strange. The Oh Vue Icons library is loading a massive 108 MB of bundle size, which significantly slows down the loading time even in ViteJS. Here's how my setup looks like: im ...

Acquiring XML data directly in jQuery without any preprocessing

Hey there, I'm dealing with an unusual situation. I need to extract data from an API that returns malformed XML. Each <episode> in the response has its own <title> tag. However, when using $.get or $.ajax, all these titles end up in the &l ...

Personalize the color scheme for your timeline paper

I am interested in customizing this specific example of a personalized timeline: import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Timeline from '@material-ui/lab/Timeline'; import Timeli ...

Execute PHP script after successful AJAX response

I've been struggling to find a solution for this issue. I have an Ajax function that continuously loops, waiting for a specific variable value. Once the variable is not equal to 0, I need to send the data to another script to update the database and t ...

Storing the array with the highest length in a temporary array using Javascript

I am currently working with two arrays that can be of equal length or one may be longer than the other. My goal is to determine the longest array if they are not equal in length, and then use this length to control a loop. $.ajax({ url: "/static/Dat ...

Discover the outcome of clicking on an object (mock tests)

I am just starting out with React and I'm unsure about when to use mocking. For instance, within the 'ListItem' component, there is a 'click me' button that reveals a dropdown for 'cameras'. Should I focus on testing what ...

AngularJS | Validate input values to ensure they fall within acceptable range for both arrow and user input types

I have a text input field where I need to limit the value between 1 and 20. Here is the HTML code snippet: <input type="number" class="form-control input-rounded" ng-model="Ctrl.new.runner" ng-change="Ctrl.newChangeAction(Ctrl.new)" ...

Using list comprehension to add a new item to a tuple

I am dealing with a numpy array arr = np.array([ [1, (10, 20, 30, 40)], [2, (10, 20, 30, 40)], [5, (11, 22, 33, 44)] ]) I am curious if there is a way to achieve : ans = [ [1, 10, 20, 30, 40], [2, 10, 20, 30, ...

What are some tips for managing the hover effect using CSS3?

Here's a demonstration of my current setup. When you hover over the black box, a transition occurs and reveals my tooltip. However, I only want the tooltip to appear when hovering over the black box itself. Currently, the transition also triggers if y ...

Encountered a cross-domain error with node.js and jQuery: ERR_CONNECTION_REFUSED

Just beginning my journey with Node.js. I've set up a basic node/express application that serves a single webpage featuring a button. When clicked, this button triggers a jQuery ajax request to an Express route. The route callback then makes an http ...

Uploading directly to AWS S3: SignatureDoesNotMatch error specifically for Internet Explorer users

My process involves using Amazon Web Service S3 for uploading and storing files. I create a pre-signed URL using the AWS SDK for Node.js on the server-side to enable direct file uploads from the browser through this signature URL. The Process On the serv ...

Utilizing useEffect to retrieve and display an empty array in a React component

I am currently developing a React application that leverages Fetch to retrieve data from an API using SQLite. Strangely, when I check the console, it only displays a length of 3 and Array[0]. This means I can't access data based on specific IDs like I ...

What steps can I take to convert my React class into a function in order to incorporate Material UI components effectively?

With Emailjs set up successfully, my next step is integrating Material UI text fields (link: https://material-ui.com/components/text-fields/#text-field) to enhance the design of my project. The challenge I'm facing is incorporating Material UI classe ...

Tips for incorporating strikethrough into a drop-down select box in a jquery datatable and implementing filtering based on it

In this scenario, I am currently utilizing a jQuery Datatable with strikethrough text. My aim is to make the filterable dropdown display the same strikethrough text; however, it is not displaying properly at the moment. Below is my jQuery datatable setup: ...

When using HTML5's checkValidity method, it may return a valid result even if

Consider the following scenario: <input pattern="[a-z]"/> If you run the command below without entering any input: document.querySelector('input').checkValidity() You will notice that it actually returns true. This seems counterintuiti ...

Encountering a problem in React when trying to install a color detection library

Hey there, I'm working on a Spotify-clone project where I want to detect the dominant color of an image and use it as the background color. Unfortunately, I've run into some errors while trying to integrate libraries like color-theif, node-vibran ...

Graphs vanish when they are displayed in concealed sections

Looking for a way to toggle between two charts (created with charts.js) by clicking a button? Initially, I had them in separate divs, one hidden and the other visible: <div id="one"> <canvas id="myChart1" width="400" height="400"></can ...

Transmitting information from the front-end Fetch to the back-end server

In my stack, I am using Nodejs, Express, MySQL, body-parser, and EJS. My goal is to trigger a PUT request that will update the counter by 1 when a button is pressed. The idea is to pass the ID of the clicked button to increment it by 1. app.put("/too ...

Dealing with multiple input fields that are generated using the map method in combination with react-redux

I am working on a project where I have a product list in JSON format stored in json-server. I am using React-Redux to fetch the data and render it in a table. Additionally, I have an input field where users can enter the quantity of each product. I need to ...