1

I am trying to convert a nested object to a string indexed object, so I can use Vue to display all properties in an object. For example:

var obj = {
  key1: 'value1',
  key2: {
    key3: {
      key5: 'value5',
      key6: 'value6'
    },
    key4: 'value4'
  }
};

Should be convert to this:

var obj = {
  'key1': 'value1',
  'key2.key3.key5': 'value5',
  'key2.key3.key6': 'value6',
  'key2.key4': 'value4'
}

I tried to walk recursively through the object, but I didn't figure out how to get the correct index value and return both the index and the object at the same time.

What I've tried so far:

// let result = objConversion(obj)
objConversion (obj) {
  let resultObject = {}
  // Walk through the first level
  for (let index in obj) {
    if (obj.hasOwnProperty(index)) {
      let extractedObj = getObjNameRecursive(obj[ index ], index)
      resultObject = { ...resultObject, ...extractedObj }
    }
  }
  return resultObject
}

getObjNameRecursive (obj, name) {
  let resultObject = {}
  if (typeof obj === 'object') {
    // Dive into an object
    for (let index in obj) {
      if (obj.hasOwnProperty(index)) {
        if (typeof obj[ 'index' ] === 'object') {
          resultObject = { ...resultObject, ...getObjNameRecursive(obj[ 'index' ], name + '.' + index) }
        } else {
          resultObject = {...resultObject, [name + '.' + index]: obj[index]}
        }
      }
    }
  } else {
    // Simple assign if not an object
    resultObject[ name ] = obj
  }
  return resultObject
}

But this gives the result like:

obj = {
  'key1': 'value1',
  'key2.key3.key5': [object Object],
  'key2.key3.key6': [object Object],
  'key2.key4': 'value4'
}

The answer in Convert string to an attribute for a nested object in javascript is very close to what I want. But what I want is to get the string of attributes of a nested object.

Is there any better way to do this?

Thanks.

Zhwt
  • 426
  • 3
  • 13

1 Answers1

2

Try this

function convert(obj, key, result) {
  if(typeof obj !== 'object') {
    result[key] = obj;
    return result;
  }
  const keys = Object.keys(obj);

  for(let i = 0; i < keys.length; i++){
    const newKey = key ? (key + '.' + keys[i]) : keys[i];
    convert(obj[keys[i]], newKey, result);
  }

  return result;
}

call it

convert(obj, '', {});
prabhatojha
  • 1,925
  • 17
  • 30