调整其他对象架构的对象模型架构

Object Model Schema to Adjust the Schema of other Objects

嗨,

问题:我如何构建一个函数:

  1. 通过参数接收对象;
  2. 这是第二个参数的模式模型;
  3. 第二个参数是一个对象数组,与第一个参数的模型不同;

Objective: return 需要是经过以下修改的对象数组:

  1. 需要删除每个元素的第一个参数(对象模型)中不存在的属性;
  2. 对于元素上不存在的属性需要用NULL值创建;
  3. 最后,每个元素的其他属性需要保持相同的值;

示例 - 调用函数:

    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'}]));

但是这个解决方案对于一般问题来说太具体了。有什么想法吗?

我认为 .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'}])
)

这接近于 map()reduce() 的单线。如果您可以 return 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)