3

I have two arrays that are:

1) listArray and it's formatted like this:

0: {value: "373", text: "1 - First Item in the Array"}
1: {value: "343", text: "2 - Second Item in the Array"}
2: {value: "376", text: "3 - Third Item in the Array"}

2) displayArray and it's formatted like this:

0: {name: "Number One", position: "373", additionalinfo: "Description Goes Here"}
1: {name: "Number Two", position: "343", additionalinfo: "Description Goes Here"}
2: {name: "Number three", position: "376", additionalinfo: "Description Goes Here"}

I would like to have the second array displayArray use information from listArray to look like this:

0: {name: "Number One", position: "1 - First Item in the Array", additionalinfo: "Description Goes Here"}
1: {name: "Number Two", position: "2 - Second Item in the Array", additionalinfo: "Description Goes Here"}
2: {name: "Number three", position: "3 - Third Item in the Array", additionalinfo: "Description Goes Here"}

I don't mind creating a third array, but when I tried to use it inside array.push, I got errors. How can I do that?

3
  • What have you tried and what errors did you get? A forEach or map should do it. Commented Mar 15, 2020 at 0:28
  • how would that be a conditional getting data from array 1 and replace array 2? Commented Mar 15, 2020 at 2:36
  • it's not an error, but rather it didn't work by replacing the position value from array 2 with the text value from array 1 Commented Mar 15, 2020 at 3:52

1 Answer 1

1

Option 1: Change displayArray

Use forEach:

displayArray.forEach((item, index) => {
  item.position = listArray[index].text;
})

Option 2: Create a new array

Use map:

const newArray = displayArray.map((item, index) => {
  const newitem = Object.assign({}, item);
  newitem.position = listArray[index].text;
  return newitem;
})

Here is a demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.