Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

132
Vistas
Merge objects in javascript into one

My issue is that I have an initial object with data in the function. The function receives params with values that are into this initial object. I need to update the initial object every time with the data, which comes from params.

The code:

export function saveLocalStorage(params = {}) {
    let state = {
        firstName: '',
        lastName: '',
        role: '',
        idToken: '',
        auth: false,
        id: '',
        email: '',
        phone: '',
        organizationId: '',
        lastVisit: '',
    }

    localStorage.setItem('donisi-new', JSON.stringify(state))
}

params have the same names as names in initial object, example:

saveLocalStorage({
  firstName,
  lastName,
  role,
  organizationId,
  auth: true,
  idToken,
  lastVisit: moment(new Date()),
})

So, for example, the first time I received the first object with params, for example:

saveLocalStorage({
  firstName: 'La La',
  lastName: 'Bla Bla'
})

and second time I received object with params:

saveLocalStorage({
  role: 'admin',
  phone: '+111111111'
})

How to update the initial state and don't delete the values and only update them?

Thanks to everybody.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

This is a function I use to merge 2 JavaScript objects:

function mergeObjects(obj, src) {
    for (var key in src) {
        if (src.hasOwnProperty(key)) obj[key] = src[key];
    }

    return obj;
}

So if you had these 2 objects:

var obj1 = {name: 'Bob', age: 30};
var obj2 = {name: 'Steve'};

And ran the function:

mergeObjects(obj1, obj2);

It would return:

{name: 'Steve', age: 30}
about 4 years ago · Juan Pablo Isaza Denunciar

0

To achieve this behaviour you can use the ES6's spread operator (...) to merge objects. It will merge the two object. The new fields will be added from both object and existing ones will be updated.

Just replace your

localStorage.setItem('donisi-new', JSON.stringify(state))

with

localStorage.setItem('donisi-new', JSON.stringify({...state, ...params}))

The order of state and params is important here. This orders means state object will be updated with new values which exist in params object.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Part of the problem with updating initial state is you have state defined in the function, so those values can't be updated. One way to address this is to pull state out into its own file and then reference it in your function.

// state.js
export default {
    firstName: '',
    lastName: '',
    role: '',
    idToken: '',
    auth: false,
    id: '',
    email: '',
    phone: '',
    organizationId: '',
    lastVisit: '',
};

Then in your function you can reference and update it as necessary. The next time you call saveLocalStorage, the state will have been updated from the previous call.

import * as state from "./state.js";

export function saveLocalStorage(params = {}) {
    /* Update state with values from params example

        for (const [key, value] of Object.entries(params)) {
            state[key] = value;
        }
    */
    localStorage.setItem('donisi-new', JSON.stringify(state))
}

I leave part of this in a comment because you may have something else in mind for updating state or before merging.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda