Skip to content

Instantly share code, notes, and snippets.

@KevinPy
Created March 22, 2018 08:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KevinPy/eeb50032e4fb0fc645a254fc176e587b to your computer and use it in GitHub Desktop.
Save KevinPy/eeb50032e4fb0fc645a254fc176e587b to your computer and use it in GitHub Desktop.
[JS] Mix Arrays / Object
////////////////////////////////////////////////////////////////
/* 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