0

I have 3 arrays:

colors = ['green', 'red', 'black'];
positionToId = [0, 32, 15];
results = ["0", "1", "2"];

And want to achieve something like this:

{results: '0', 'positionToId: '31', colors: 'black'},
{results: '1', 'positionToId: '2', colors: 'red'},
{results: '2', 'positionToId: '11', colors: 'black'}

How can I do that? Thanks.

lucascaro
20.1k4 gold badges43 silver badges48 bronze badges
asked Nov 11, 2018 at 1:26
3

3 Answers 3

1

You want to merge these arrays into an array of objects with key => value.

Easiest way is to map one of them.

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

Example:

colors = ['green', 'red', 'black'];
positionToId = [0, 32, 15];
results = ["0", "1", "2"];
console.log(results.map((result,i) => {
 return {
 results: results[i], 
 positionToId: positionToId[i],
 colors: colors[i],
 };
}));

answered Nov 11, 2018 at 22:51
Sign up to request clarification or add additional context in comments.

Comments

0

Since you have an array results that you seem to want to use as your base and you want to replace these numbers, with objects keyed by the values already there I would just reduce them.

colors = ['green', 'red', 'black'];
positionToId = [0, 32, 15];
results = ["0", "1", "2"];
const newObject = results.reduce((acc, index) => ({
 ...acc,
 [index]: {
 positionToId: positionToId[index],
 colors: colors[index],
 }
}), {})

This also has the benefit of allowing you to access your items by id without having to loop over an array checking each of the id's

answered Nov 11, 2018 at 22:57

Comments

0

const colors = ['green', 'red', 'black'];
const positionToId = [0, 32, 15];
const results = ["0", "1", "2"];
const addProperties = (properties, name, results) => properties.reduce((results, property, index) => {
 results[index][name] = property;
 return results;
}, results);
let output = Array.from(Array(3), () => ({}));
addProperties(colors, 'colors', output);
addProperties(positionToId, 'positionToId', output);
addProperties(results, 'results', output);
console.log(output)

answered Nov 11, 2018 at 23:02

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.