1

is there any native way in js to transform an object from

{
    sample:{
        name:"joe",
        age:69
    }
}

to

{ 'sample.name': 'joe', 'sample.age': 69 }

i tried the following and it works for now but i'm not sure if this is the optimal way to do it

let test = {
  sample: {
    name: 'joe',
    age: 69,
  },
}

for (let [pKey, pValue] of Object.entries(test)) {
  for (let [key, value] of Object.entries(pValue)) {
    delete Object.assign(test, {
      [pKey + '.' + key]: value,
    })
    delete test[pKey]
  }
}

console.log(test);
Barmar
  • 741,623
  • 53
  • 500
  • 612

1 Answers1

0

As I asked above in the comments; why do you think you want to do this?

If it is because you actually want to access the object using a dot delimited string

const name = { sample: { name: "joe", age: 69 } }['sample.name'];

then see: Convert a JavaScript string in dot notation into an object reference.

Be warned that the accepted answer offers a long explanation as to why that is bad practice (and if the accessing is, then the remapping as you've illustrated certainly is worse).


If having read that answer you still feel that you need to remap and flatten the object then you may as well make it work for arbitrarily deep objects.

const input = {
  sample: {
    name: 'joe',
    age: 69,
    favorite: {
      food: 'pie',
      colors: ['pink', 'yellow']
    },
    birthday: (new Date(1980, 2, 18)) // excluded from result because Object.entries(Date).length === 0
  }
};

function recursivelyCombineKeys(obj) {
  const res = {};

  for (const [k, v] of Object.entries(obj)) {
    if (typeof v === 'object') {
      for (const [_k, _v] of Object.entries(recursivelyCombineKeys(v))) {
        res[`${k}.${_k}`] = _v
      }
    } else {
      res[k] = v
    }
  }

  return res
}

console.log(recursivelyCombineKeys(input));

Note: The generic typeof v === 'object' check will match a number of built-in objects such as Date and null, and will also match arrays, so you may need to narrow it. see: Check if a value is an object in JavaScript

pilchard
  • 12,414
  • 5
  • 11
  • 23