Created
March 22, 2018 08:14
-
-
Save KevinPy/eeb50032e4fb0fc645a254fc176e587b to your computer and use it in GitHub Desktop.
[JS] Mix Arrays / Object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//////////////////////////////////////////////////////////////// | |
/* Combine 2 arrays in Object with key */ | |
//////////////////////////////////////////////////////////////// | |
const arr1 = ['01', '02', '03']; | |
const arr2 = ['10', '20', '30']; | |
let obj = arr1.map((item, i) => { | |
return { | |
arr1: item, | |
arr2: arr2[i] | |
}; | |
}); | |
// Output | |
/* | |
[{ | |
arr1: "01", | |
arr2: "10" | |
}, { | |
arr1: "02", | |
arr2: "20" | |
}, { | |
arr1: "03", | |
arr2: "30" | |
}] | |
*/ | |
//////////////////////////////////////////////////////////////// | |
/* Object from 2 arrays */ | |
//////////////////////////////////////////////////////////////// | |
const keys = ['foo', 'bar', 'baz']; | |
const values = [11, 22, 33] | |
let result = {}; | |
keys.forEach((key, i) => result[key] = values[i]); | |
// Output | |
/* | |
{ | |
"foo": 11, | |
"bar": 22, | |
"baz": 33 | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment