简体   繁体   中英

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?

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

Zipping two (or more) arrays together is quite a common 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM