Question: How can I build a function that:
Objective: The return need be a array of objects with this modifications:
Example - call function:
padronizarCom({id: 1, nome:'abcd'}, [{nome:'Carlos', idade:30}, {a:'x', b:'y', c:'z'}])
// **output:**
// 0:{nome: "Carlos", id: null}
// 1:{nome: null, id: null}
const padronizarCom = (object,array) => array.reduce(
(accum, { id, nome}, i) => (
{
...accum,
[i]: {id, nome}
}),
{}
);
console.log(padronizarCom({id: 1, nome:'abcd'}, [{nome:'felipe', idade:27}, {a:'x', b:'y', c:'z'}]));
This is close to a one-liner with map()
and reduce()
. It would be easier if you could return undefined
instead of null
for non-existent keys:
function padronizarCom(schema, obj) {
return obj.map(item => Object.keys(schema)
.reduce((a, key) => (a[key] = (item[key] !== undefined ? item[key] : null), a), {}))
}
let ret = padronizarCom({id: 1, nome:'abcd'}, [{nome:'Carlos', idade:30}, {a:'x', b:'y', c:'z'}])
console.log(ret)