Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

131
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda