Search code examples
javascriptarraysecmascript-6javascript-objectsecmascript-5

Object Model Schema to Adjust the Schema of other Objects


Hi,

Question: How can I build a function that:

  1. Recive a object by argument;
  2. It's a schema model for the second argument;
  3. The second argument is a array of objects that has not the same model of the first argument;

Objective: The return need be a array of objects with this modifications:

  1. Need be removed each of each element the properties that does't exist on the first argument (the object model);
  2. For the properties that doesn't exist on element need be created with NULL value;
  3. Finally, the other properties of each element need persist with the same value;

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

But this solution is too specific to a generic problem. any ideia ?


Solution

  • 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)