Home > Software engineering >  Creating new array of objects from existing arrays, matching on index
Creating new array of objects from existing arrays, matching on index

Time:05-11

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?

CodePudding user response:

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

CodePudding user response:

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>`)

  • Related