Tengo una matriz de objetos que me gustaría transformar en un solo objeto js. La matriz contiene el valor objetivo y la matriz de claves. Nota: quiero que esto funcione en vanilla js sin importar scripts.
La matriz de origen:
[ { value: 'res-1', keys: [ 'first' ] }, { value: 'res-2', keys: [ 'second', 'deeperOne' ] }, { value: 'res-3', keys: [ 'second', 'deeperTwo' ] }, { value: 'res-4', keys: [ 'second', 'deeperThree', 'moreDeeper' ] }, { value: 'res-5', keys: [ 'third' ]} ]Resultado deseable (objeto):
{ first: 'res-1', second: { deeperOne: 'res-2', deeperTwo: 'res-3', deeperThree: { moreDeeper: 'res-4' } }, third: 'res-5' }cmgchess respondió a la pregunta con un comentario. ¡Aquí está el código!
const array = [ { value: 'res-1', keys: [ 'first' ] }, { value: 'res-2', keys: [ 'second', 'deeperOne' ] }, { value: 'res-3', keys: [ 'second', 'deeperTwo' ] }, { value: 'res-4', keys: [ 'second', 'deeperThree', 'moreDeeper' ] }, { value: 'res-5', keys: [ 'third' ]} ] const set = (obj, path, value) => { path.reduce((acc, key, i) => { if (acc[key] === undefined) acc[key] = {} if (i === path.length - 1) acc[key] = value return acc[key] }, obj) } let object = {} array.forEach(({value, keys}) => set(object, keys, value)) console.log(object)