Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

209
Views
Creating new array of objects from existing arrays, matching on index

I have two arrays, and presently I am combining them into one array like so:

const changeArr = selectedReasons.map((e, i) => e + changeComments[i]);

That works, but what I'd ideally like to do is, rather than mashing them into one element, is create an array of objects, where each object has a property referencing the first array, and the second property being the corresponding index element from the second array.

So imagine the first array looks like this:

selectedReasons = [
  "100A",
  "100B"
]

And the second one looks like this:

changeComments = [
  "Here is my clarifying comment for the first choice.",
  "This is a different comment pertaining to my second choice."
]

What I'd like to end up with is this:

changeArr = [
  {
    reason: "100A",
    comment: "Here is my clarifying comment for the first choice."
  },
  {
    reason: "100B",
    comment: "This is a different comment pertaining to my second choice."
  }
]

How can I adjust my current code which mashes together elements into an array of objects with two properties for each object, that match based on the index of the elements?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You could loop from 0 to the end of the reasons array, and push new objects to a new array using the reason and comment at index i from their respective other arrays, like so:

let changeArr = [];
for (let i = 0; i < selectedReasons.length; i++) {
    changeArr.push({ reason: selectedReasons[i], comment: changeComments[i] });
}

This does mean that if the selectedReasons array and the changeComments array are not the same length, you might run into problems

about 4 years ago · Juan Pablo Isaza Report

0

You simply need to return an object

var selectedReasons = [
  "100A",
  "100B"
]

var changeComments = [
  "Here is my clarifying comment for the first choice.",
  "This is a different comment pertaining to my second choice."
]


var result = selectedReasons.map((reason, i) => ({
  reason,
  change: changeComments[i]
}))

document.write(`<pre>${JSON.stringify(result, null, 2)}</pre>`)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!