Home > Software engineering >  Make nested object by flatten path
Make nested object by flatten path

Time:04-09

I've got such nested object

{

"incl_1_1": "val_incl_1_1",

"incl_1_2": "val_incl_1_2",

"incl_1_1_child": {

"incl_2_1": "val_incl_2_1",

"incl_2_2": "val_incl_2_2",

},

"incl_1_2_child": {

"incl_2_1": "val_incl_2_1",

"incl_2_2": "val_incl_2_2",

}
}

wrote recursive function to flatten it, so i've got

{
  incl_1_1: 'val_incl_1_1',
  incl_1_2: 'val_incl_1_2',
  'incl_1_1_child.incl_2_1': 'val_incl_2_1',
  'incl_1_1_child.incl_2_2': 'val_incl_2_2',
  'incl_1_2_child.incl_2_1': 'val_incl_2_1',
  'incl_1_2_child.incl_2_2': 'val_incl_2_2'
}

now i need to write function to get original nested object from flatten one and I'm stuck

CodePudding user response:

You could take a recursive approach and build at the end an object from entries.

const
    getEntries = object => Object
        .entries(object)
        .flatMap(([k, v]) => v && typeof v === 'object'
            ? getEntries(v).map(([l, v]) => [`${k}.${l}`, v])
            : [[k, v]]
        ),
    data = { a: "aa", b: "bb", c: { d: "dd", e: "ee" }, f: { g: "gg", g: "gg", h: { i: 'ii' } } },
    result = Object.fromEntries(getEntries(data));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

CodePudding user response:

You can do something like this for the example you provided.

const obj = {
  incl_1_1: 'val_incl_1_1',
  incl_1_2: 'val_incl_1_2',
  'incl_1_1_child.incl_2_1': 'val_incl_2_1',
  'incl_1_1_child.incl_2_2': 'val_incl_2_2',
  'incl_1_2_child.incl_2_1': 'val_incl_2_1',
  'incl_1_2_child.incl_2_2': 'val_incl_2_2'
}

const original={}
const keys = Object.keys(obj)


for(let i=0; i<keys.length; i  ){
  let prop, nested
  if (!keys[i].includes(".")){
    original[keys[i]] = obj[keys[i]] 
  } else {
    prop= keys[i].split('.')[0]
    nested = keys[i].split('.')[1]
    original[prop] ? original[prop][nested] =obj[keys[i]] : original[prop] = {[`${nested}`]: obj[keys[i]]}
  }
}

console.log(original)

  • Related