admin管理员组文章数量:1400456
I have two arrays that look like this:
array1 = ["org1", "org2", "org3"];
array2 = ["a", "b", "c"];
Using JavaScript, I want to convert two arrays of same length into array of objects that would look like this:
orgMSPID = [{"org1": "a"},{"org2": "b"}, {"org3": "c"}]
Please anybody suggest me how to convert it?
I have two arrays that look like this:
array1 = ["org1", "org2", "org3"];
array2 = ["a", "b", "c"];
Using JavaScript, I want to convert two arrays of same length into array of objects that would look like this:
orgMSPID = [{"org1": "a"},{"org2": "b"}, {"org3": "c"}]
Please anybody suggest me how to convert it?
Share Improve this question edited Jan 7, 2021 at 15:12 VLAZ 29.1k9 gold badges63 silver badges84 bronze badges asked Jan 7, 2021 at 15:11 AbhiSamAbhiSam 1051 silver badge7 bronze badges4 Answers
Reset to default 6You can use Array.map() to iterate the array1
and use []
for the dynamic key of the object.
const array1 = ["org1", "org2", "org3"];
const array2 = ["a", "b", "c"];
const orgMPSID = array1.map((key, index) => ({ [key]: array2[index] }));
console.log(orgMPSID);
Zipping two (or more) arrays together is quite a mon operation. If you use a library with helpers, chances are big that it includes a helper function for this (often named zip
). If you aren't using a helper library consider adding a zip
function yourself.
zip([1,2,3], [4,5,6]) //=> [[1,4], [2,5], [3,6]]
Each entry within this result can then easily be transformed into an object using any of the lines below:
entries.map(entry => Object.fromEntries(Array.of(pair)));
entries.map(entry => Object.fromEntries([entry]));
entries.map(([key, value]) => ({ [key]: value }));
const zip = (...args) => args[0].map((_, i) => args.map(arg => arg[i]));
const array1 = ["org1", "org2", "org3"];
const array2 = ["a", "b", "c"];
const result = zip(array1, array2).map(([key, value]) => ({ [key]: value }));
console.log(result);
let array1 = ["org1", "org2", "org3"];
let array2 = ["a", "b", "c"];
let array3 = [];
for(let i=0; i< array1.length; i++){
let item = {};
item[array1[i]]=array2[i];
array3.push(item)
}
console.log(array3);
You can use Array.prototype.reduce()
.
You iterate through array1
, and use the current index to reference array2
(or you could flip it the other way instead).
const array1 = ["org1", "org2", "org3"];
const array2 = ["a", "b", "c"];
const orgMSPID = array1.reduce((c, e, i) => {
c.push({ [e] : array2[i] });
return c;
}, []);
console.log(orgMSPID);
本文标签: How to convert two array into map in javascriptStack Overflow
版权声明:本文标题:How to convert two array into map in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744203059a2595057.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论