admin管理员组文章数量:1429987
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"
}];
Share
Improve this question
edited Jul 13, 2018 at 11:19
mesopotamija9
asked Jul 13, 2018 at 11:18
mesopotamija9mesopotamija9
336 bronze badges
3
- 4 what did you try? – Giannis Mp Commented Jul 13, 2018 at 11:18
- I made one empty array containing certain number of objects like this c = [{ a: 0, b: 0 },{ a: 0, b: 0 },{ a: 0, b: 0 }] and then with for loop i filed in data but this is really bad if I had 100+ arrays – mesopotamija9 Commented Jul 13, 2018 at 11:21
- 1 Check Nikhil's answer – Giannis Mp Commented Jul 13, 2018 at 11:22
6 Answers
Reset to default 5You 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 can use Array.forEach()
loop for that:
var a = [1, 2, 3];
var b = ["a", "b", "c"];
var c = [];
a.forEach((item, index)=>{
c.push({a: item, b: b[index]});
});
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; }
Traditional but patible way
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 bine(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;
}
bine(a, b); // Use it like a function
本文标签: javascriptMultiple arrays transformed to objects to one array with Node JSStack Overflow
版权声明:本文标题:javascript - Multiple arrays transformed to objects to one array with Node JS - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745481840a2660208.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论