Reputation: 105
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?
Upvotes: 6
Views: 2272
Reputation: 21110
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);
Upvotes: 1
Reputation: 5237
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);
Upvotes: 0
Reputation: 126
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);
Upvotes: 0
Reputation: 8751
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);
Upvotes: 6