-2

I need to fill a JSON where their properties have the same name with the attributes of the object.

MyObject:

{ idCliente: 4,
  idAplicacionEmpresa: 1,
  email: 'Jaa@jo.com',
  nombre: 'Joaquin',
  apellido: 'Diaz',
}

MyJSON:

{ sexo: '',
  nombre: '',
  apellido: '',
  telefono: '',
  documento: '',
  provincia: '',
  fechaNacimiento: '',
  localidadResidencia: '' 
}

Only fill properties who match.

Im using a promise to generate a pdf from a template where the fields of the form match with de json properties, here is my code

TramitePdf.generatePdf = function (idTipoTramite, idCliente, callback) {
var cliente = TramitePdf.app.models.Cliente;
var modeloTipoTramite = TramitePdf.app.models.TipoTramite;
var pathModelo, pathCliente, tipoT, clienteActual;
modeloTipoTramite.findById(idTipoTramite)
  .then(tipoTramite => {
    this.pathModelo = `${__dirname}/../pdf/${tipoTramite.nombre}.pdf`;
    this.pathCliente = `${__dirname}/../pdf/clientes/${idCliente}_${idTipoTramite}_${tipoTramite.nombre}.pdf`;
    this.tipoT = tipoTramite;
    this.clienteActual = cliente.findById(idCliente);
    return this.clienteActual;
  })
  .then(cliente => {
    pdfFiller.fillForm(this.pathModelo, this.pathCliente, JSON.parse(this.tipoT.template), function (err) {
      callback(err, cliente);
    });
  })
  .catch(err => {
    callback(err);
  });

};

Any ideas?

2 Answers2

1

Just:

Object.keys(someJson).forEach(el => {
  if (typeof myJson[el] !== 'undefined') {
    myJson[el] = someJson[el];
  }
});
Lazyexpert
  • 3,106
  • 1
  • 19
  • 33
0

you can try this

let a = { idCliente: 4,
  idAplicacionEmpresa: 1,
  email: 'Jaa@jo.com',
  nombre: 'Joaquin',
  apellido: 'Diaz',
}

let b = { sexo: '',
  nombre: '',
  apellido: '',
  telefono: '',
  documento: '',
  provincia: '',
  fechaNacimiento: '',
  localidadResidencia: '' 
}
console.log(b,a)
let KeysOf_a = Object.keys(a);

for(let i = 0;i < KeysOf_a.length;i++){
  if(b.hasOwnProperty(KeysOf_a[i])){
    b[KeysOf_a[i]] = a[KeysOf_a[i]]
  }
}

console.log(b,a)
meeran jasir
  • 89
  • 1
  • 9