1

I currently have an array of string values: const array1 = ['string1', 'string2'];

I want to be able to use the strings from this array and create a new array with nested objects that use them as the values for the object keys. Like this:

const array2 = [{value: 'string1', label: 'string1'}, {value: 'string2', label: 'string2' ];

I've tried using the .reduce() method and currently, my code looks like this:

const arr = ['string1', 'string2'];
const newArr = [];

function reducer(acc, cur) {
  return {...acc, [cur.id]: cur};
}

const reducedArr = arr.reduce(reducer, {});
newArray.push(reducedArr);

When I log newArray to the console I'm getting back:

Array [{ undefined: 'string2'}]

What is the best way to solve this problem?

0

1 Answer 1

1

Each element in array2 is a mapping of each element of array1.

const array1 = ['string1', 'string2'];
const array2 = array1.map(item => ({value: item, label: item}));
console.log(array2);

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

1 Comment

Thank you! I realized right after I posted that I should be mapping over it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.