Transforming object objects into a single-level object

Asked

Viewed 36 times

0

All right?

Currently I have a function that transforms strings into objects, give a split(".") and pass the array as parameter, show, I have my object filled.

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 proposal = {
  id: 123,
  customer: {
   name: "Fulano",
   lastName: "Da Silva",
   address: {
     street: ""
   }
  }
}
let string = "customer.address.street";
let obj = changeObject(string.split("."), "Rua ABC", proposal)
// retorna meu objeto proposal com street preenchido "Rua ABC"

But I also need a function that transforms this object with several levels into an object with only one level where the levels are separated by Ex points:

//O Objeto Antes estaria assim
let proposal = {
  id: 123,
  customer: {
   name: "Fulano",
   lastName: "Da Silva",
   address: {
     street: "Rua ABC"
   }
  }
}

//Após passar pela função o objeto proposal estaria assim ou retornaria um novo objeto assim:

proposal = {"customer.name": "Fulano", "customer.lastName": "Da Silva", "customer.address.street": "Rua ABC"}

I guess I’d have to use recursion

  • Take a look at this answer here. I think that’s what you want.https://stackoverflow.com/questions/44134212/best-way-to-flatten-js-object-keys-and-values-to-a-single-depth-array

  • Ball Show... Obg Calixto. The flattenObject function was what I needed

No answers

Browser other questions tagged

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