0

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 ?

Community
  • 1
  • 1

2 Answers2

0

I think .map is a better function for this as you are mapping one array to another.

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'}])
)
Mikey
  • 6,728
  • 4
  • 22
  • 45
  • 1
    Small edge case: `{nome:'Carlos', id:0}` in the input will return `{nome:'Carlos', id:null}` – Mark May 20 '18 at 01:30
0

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)
Mark
  • 90,562
  • 7
  • 108
  • 148