问题:如何构建以下功能:
目标:返回需要是具有此修改的对象数组:
示例 - 调用函数:
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'}]));
答案 0 :(得分:0)
我认为.map是一个更好的函数,因为你将一个数组映射到另一个数组。
function padronizarCom(schema, array) {
let keys = Object.keys(schema);
return array.map(obj => {
let newObj = {};
// build new object using keys from schema
keys.forEach(key => {
// use existing object's key if it exist; otherwise null
newObj[key] = obj.hasOwnProperty(key) ? obj[key] : null;
});
return newObj;
});
}
console.log(
padronizarCom({id: 1, nome:'abcd'}, [{nome:'Carlos', idade:30 }, {a:'x', b:'y', c:'z'}])
)

答案 1 :(得分:0)
这接近map()
和reduce()
的单行。对于不存在的密钥,如果您可以返回undefined
而不是null
会更容易:
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)