-1

I have a JSON object which is

let data = {
 "key1" : 1,
 "key2" : 2,
 "subKeys":{
  "subKey1" : 3,
  "subKey2" : 4
  }
}

I want my resultant JSON like this structure:

let resultantData = {
 "key1":1,
 "key2":2,
 "subKey1":3,
 "subKey2":4
}

How can I achieve this goal

3 Answers3

1

This should do it for you:

Object.entries(data).forEach(([key, val]) => {
  if (typeof val === 'object' && !Array.isArray(val)) {
    // if the item is an object and not an array, copy over the values.
    Object.entries(val).forEach(([subKey, subVal]) => {
      data[subKey] = data[subVal];
    });
    // delete original child object.
    delete data[key];
  }
})
RoryH
  • 90
  • 5
1

Assuming you're using a fairly recent version of a JavaScript runtime due to the 'let' statement.

There are a couple of ways of doing this but the most direct is to merge the two hashes and then delete the key 'subKeys'.

I found this in another SO article. Please upvote if it helps.

let data = {
    "key1" : 1,
    "key2" : 2,
    "subKeys":{
     "subKey1" : 3,
     "subKey2" : 4
     }
   };

let merged = { ...data, ...data['subKeys']};

delete merged['subKeys']

console.log(merged);
Dave G
  • 9,639
  • 36
  • 41
1

To make this method more dynamic, you can use a recursive approach to flatten deeply nested objects with multiple levels. You can do this by taking the object's entries, and mapping them until no [key, value] pair array has a value which is an object by recursively mapping the object value's entires. To show this, I've added an additional nested object within your subKeys object called subsubKeys:

const data = { "key1" : 1, "key2" : 2, "subKeys":{ "subKey1" : 3, "subKey2" : 4, "subsubKeys": {"subsubKey1": 100}, "subKey3": 5 } };
const getEntries = obj => Object.entries(obj).flatMap(
  ([key, val]) => Object(val) === val 
    ? getEntries(val) 
    : [[key, val]]
);

const flattenObj = obj => Object.fromEntries(getEntries(obj));
console.log(flattenObj(data));
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64