For example I have this arrays:
a = [1, 2, 3];
b = ["a", "b", "c"];
I want to make one object from these arrays that would look like this:
c = [{
a: 1,
b: "a"
},
{
a: 2,
b: "b"
},
{
a: 3,
b: "c"
}];
For example I have this arrays:
a = [1, 2, 3];
b = ["a", "b", "c"];
I want to make one object from these arrays that would look like this:
c = [{
a: 1,
b: "a"
},
{
a: 2,
b: "b"
},
{
a: 3,
b: "c"
}];
You can use Array.map
let a = [1, 2, 3];
let b = ["a", "b", "c"];
let c = a.map((v,i) => ({a:v, b: b[i]}));
console.log(c);
You can use Array#reduce to do something like this perhaps:
var a = [1, 2, 3];
var b = ["a", "b", "c"];
var c = a.reduce((accumulator, e, index) => {
return accumulator.concat({a: e, b: b[index]});
}, [])
console.log(c);
You can use a for-loop like this:
var a = [1, 2, 3];
var b = ["a", "b", "c"];
var c = [];
for (var i = 0; i < a.length; i ++) {
c[i] = {'a': a[i], 'b': b[i]};
}
console.log(c);
You could take an object with an arbitrary count of properties and generate an array of objects.
var a = [1, 2, 3],
b = ["a", "b", "c"],
result = Object
.entries({ a, b })
.reduce((r, [k, a]) => {
a.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; }
Note: Most solutions in this page don't check if variables a and b have the same length
var a = [1, 2, 3];
var b = ["a", "b", "c"];
function combine(a,b){
if (a.length === b.length){ // Check if both arrays have same length
var arr = []; // Make an empty array
for(var i=0; i<a.length; i++){ // iterate every element of the array
var obj = {} // Make an empty object
obj["a"] = a[i];
obj["b"] = b[i];
arr.push(obj);
}
}else{
throw "Arrays don't have the same length";
}
return arr;
}
combine(a, b); // Use it like a function