Reputation: 1129
I have this code below consisting of 2 arrays with key pair values. What i'm currently trying to achieve is to combine this arrays into something like this.
[{"id" : "1" , "alphabet" : "A"}, {"id" : "2" , "alphabet" : "B"}, {"id" : "3" , "alphabet" : "C"}, ]
Is there any easy way to achieve this? Any help would be greatly appreciated thank you.
var arr = [1,2,3,4,5,6,7,8,9]
var array = arr.map((x) => ({ id:x }));
console.log(array);
var arr2 = ['A','B','C','D','E','F','G','H','I']
var array2 = arr2.map((x) => ({ alphabet:x }));
console.log(array2);
Upvotes: 4
Views: 130
Reputation: 386868
A much more easier way with different length of value arrays and with the potential to add some more arrays is to use an object with the keys as wanted key for the properties for the wanted new objects.
It works by using short hand properties and later get the property name as key for the new object and the value as array for single values of the new object.
Inside of reduce, all values of the arrays are combined to a new object and assigned to the object at the same index. If that object does not exist, a new object is used.
var id = [1, 2, 3, 4, 5, 6, 7, 8, 9],
alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'],
result = Object
.entries({ id, alphabet })
.reduce((r, [k, values]) => {
values.forEach((v, i) => Object.assign(r[i] = r[i] || {}, { [k]: v }));
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 0
Reputation: 68933
Pass index as the second parameter in map()
so that you can use that to take the number from the specific index. Try the following:
var arr = [1,2,3,4,5,6,7,8,9]
var arr2 = ['A','B','C','D','E','F','G','H','I']
var array2 = arr2.map((x,i) => ({id:arr[i], alphabet:x }));
console.log(array2);
OR: if the length of the arrays are not same:
var arr = [1,2,3,4,5]
var arr2 = ['A','B','C','D','E','F','G','H','I']
var array2 = arr2.map(function(x,i){
arr[i] = arr[i] || '';
return {id:arr[i], alphabet:x}
});
console.log(array2);
Upvotes: 1
Reputation: 5522
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var arr2 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'];
var finalResult = arr.reduce((array, val, index) => {
arr2[index] ? array.push({
id: val,
alphabet: arr2[index]
}) : null;
return array;
}, []);
console.log(finalResult);
Upvotes: 0
Reputation: 28475
Use Array.map
var arr = [1,2,3,4,5,6,7,8,9]
var arr2 = ['A','B','C','D','E','F','G','H','I']
var result = arr.map((v,i) => ({id:v, alphabet:arr2[i]}));
console.log(result);
Upvotes: 5