javascript – I have to return the unique properties of each received object (I don't know if the code is well written)

Question:

I used as an example 2 obja and objb objects and knowing their properties I can do the return, what I would like to know is if the function receives 2 or more objects with different properties, how do I write the code to return those properties that are unique to each object? Thanks in advance.

 function clavesUnicas(obj1, obj2) {
        // La funcion recibe dos objetos "obj1" y "obj2".
        // Retornar las keys de las propiedades que sean únicas en cada objeto.
        // Ej:
        // let obj1 = {nombre: "Luciano", apellido: "Nicolau"}
        // let obj2 = {nombre: "Lio", segundoNombre: "Gustavo"}
        // clavesUnicas(obj1, obj2) retorna => ["apellido", "segundoNombre"];
        //
        // Tu código`:
      
         let obja = {nombre: "Luciano", apellido: "Nicolau"};
      
         let objb = {nombre: "Lio", segundoNombre: "Gustavo"};
      
      var unica = clavesUnicas.filter(function(elemento){
        
        return obja.apellido && objb.segundoNombre;
        
      })
      
      return unica;
    };

Answer:

You can use set() to get the unique keys:

 let obja = { nombre: "Luciano", apellido: "Nicolau" }; let objb = { nombre: "Lio", segundoNombre: "Gustavo" }; let unicos = Array.from(new Set(Object.keys({ ...obja, ...objb }))) console.log(unicos)

In steps this would look like this:

 let obja = { nombre: "Luciano", apellido: "Nicolau" }; let objb = { nombre: "Lio", segundoNombre: "Gustavo" }; //Creamos un solo objeto con las llaves. let nuevoObjeto = { ...obja, ...objb } //Obtenemos solo los las claves let claves = Object.keys(nuevoObjeto) let sinDuplicados = new Set(claves) //Esto es por que el set tienen operaciones diferentes que //array. let nuevoArreglo = Array.from(sinDuplicados) console.log(nuevoArreglo)
Scroll to Top