I'm trying to write a function that takes an array of objects, and an unlimited number of arrays, and combines them to form a single object. The inputs would follow this pattern:
let x = [{ name: 'Tom' }, { name: 'John' }, { name: 'Harry' }]; let y = [[1, 2, 3], 'id']; let z = [['a', 'b', 'c'], 'value']; combine(x, y, z); With the second element of y and z acting as the object key. Using these arguments, the function should return the following array:
[ { name: 'Tom', id: 1, value: 'a' }, { name: 'John', id: 2, value: 'b' }, { name: 'Harry', id: 3, value: 'c' }, ] The index of the current object should be used to get the correct element in the array. I have made an attempt at the problem:
function combine(object, ...arrays) { return object.map((obj, index) => { let items = arrays.map(arr => ({ [arr[1]]: arr[0][index] })); return Object.assign({}, obj, { items }); }); } This almost does the job, but results in the array items being hidden inside a nested items array, How can I solve this?
mapcheck Demo