Changing an Existing Object

Asked

Viewed 38 times

1

Tudo Bom?

I am trying to change an existing object by inserting new values in it.

Ex:

// Tenho um Objeto Values
let values = {
 customer: {
   name: "Fulana",
   address: {
     street: "Rua D"
   }
 }
}

I need a function where I can pass this object, a path and a new value per parameter. The path is the place where I want to store my new value (Ex: ["Customer" "address", "number"])

At the moment I only have the function that will generate an object for me, but I do not know how to change this object without losing the existing values

//função para criar objeto

    changeObject(path, value){ // path = ["customer", "address", "number"] value = "34"
        let curr = value;
        for(let i=path.length-1; i >= 0; i--){
            let o = {};
            o[path[i]] = curr;
            curr = o;
        }
        return curr;
    }

//Depois de passar pela função quero que retorne algo assim
values = {
 customer: {
   name: "Fulana",
   address: {
     street: "Rua D",
     number: 34,
   }
 }
}

Currently I only have the function that generates the object

1 answer

1


I usually have a similar function in my toolbox, but I usually use the API fn('chave1.chave2.chave3', valor).

In addition to being a good idea to pass the object as an argument (and beware of the fact that the initial object outside the function, because it is changed by reference!), you need to use it curr[key] = curr[key] || {} not only overwrite the value of the sub-object, but use it if it already exists.

You can do it like this:

function changeObject(path, value, obj = {}) {
  const lastKey = path.pop();
  let curr = obj;
  for (let key of path) {
    curr = curr[key] || {};
  }
  curr[lastKey] = value;
  return obj;

}

let values = {
  customer: {
    name: "Fulana",
    address: {
      street: "Rua D"
    }
  }
}

const alterado = changeObject(["customer", "address", "number"], "34", values);
console.log(alterado);

A safer version, where the initial object is not changed could be like this:

function changeObject(path, value, obj = {}) {
  const lastKey = path.pop();
  const changed = {...obj};
  let curr = changed;
  for (let key of path) {
    curr[key] = curr[key] ? {...curr[key]} : {};
    curr = curr[key];
  }
  curr[lastKey] = value;
  return changed;
}

let inicial = {
  customer: {
    name: "Fulana",
    address: {
      street: "Rua D"
    }
  }
}

const alterado = changeObject(["customer", "address", "number"], "34", inicial);
console.log(alterado);
console.log(inicial);

  • 2

    Vlw Sergio, Tu é brabo. Tmj ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.