Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

How to convert two array into map in javascript

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You 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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...