Reputation: 1070
I have two arrays (x
,y
) with some number sequence, both arrays are from the same length. Now I need to combine the elements of both two arrays to a object. To create the object I have a function f
How can I quickly convert it to a single array of objects
x = [1,2,3,4]
y = [5,6,7,8]
f = function(x,y) { return { foo: x, bar: y } }
... some magic ...
result = [{ foo: 1, bar: 5},
{ foo: 2, bar: 6},
{ foo: 3, bar: 7},
{ foo: 4, bar: 8}]
Of course this is possible using
const array = []
for (let i = 0; i <= x.length; i++) {
array.push(f(x[i],y[i]))
}
But I want to know if there is a more 'cleaner' way? Using .map for instance? Or would this be the way to go?
-Edit- Thanks everyone, didn't knew map
could also pass the index as parameter.
Upvotes: 0
Views: 1002
Reputation: 386520
You could build an object with the names of the variables as keys and iterate all entries of the object and take the index of the arrays as index for the object of the result array.
This works for arbitrary length of the arrays.
var foo = [1, 2, 3, 4],
bar = [5, 6, 7, 8],
result = Object
.entries({ foo, bar })
.reduce((r, [k, a]) => a.map((v, i) => Object.assign(r[i] || {}, { [k]: v })), []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 3
Reputation: 549
You can use map function.But it is just a syntactic sugar for this problem
x = [1,2,3,4];
y = [5,6,7,8];
console.log(x.map((el,i) => ({foo:el,bar:y[i]})));
.
Upvotes: 1
Reputation: 50291
Use reduce
method on any one array and use it's index to get the element from the another array.
x = [1, 2, 3, 4]
y = [5, 6, 7, 8]
f = function(x, y) {
return x.reduce(function(acc, curr, index) {
let m = {}; //creating an array which will have two keys
m.foo = curr,
m.bar = y[index];
acc.push(m);
return acc;
}, []);
}
console.log(f(x, y))
You can also use map
method which return an array , so inside the map call back function just create the object and return it
x = [1, 2, 3, 4]
y = [5, 6, 7, 8]
f = function(x, y) {
return x.map((item, index) => {
return {
foo: item,
bar: y[index]
}
})
}
console.log(f(x, y))
Upvotes: 2