-4

My JSON object data:

{
    "title": "aa",
    "desc": ["i", "j", "k"],
    "cnt": {
        "head": "bb",
        "main": {
            "num1": {
                "time1": "mm",
                "time2": "kk"
            },
            "num2": "dd"
        }
    }
}

My question is: How do I translate the above JSON object to the below by using JavaScript?

{
    "title": "aa", 
    "desc": ["i", "j", "k"],
    "cnt_head": "bb",
    "cnt_main_num1_time1": "mm",
    "cnt_main_num1_time2": "kk",
    "cnt_main_num2": "dd"
}

I tried using for(i in obj) {....} but failed!

Please help!

hijack
  • 381
  • 3
  • 11
  • 6
    The posted question does not appear to include [any attempt](https://idownvotedbecau.se/noattempt/) at all to solve the problem. StackOverflow expects you to [try to solve your own problem first](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users), as your attempts help us to better understand what you want. Please edit the question to show what you've tried, so as to illustrate a specific roadblock you're running into a [MCVE]. For more information, please see [ask] and take the [tour]. – CertainPerformance Dec 28 '18 at 03:06
  • 1
    If you have made attempts using `for(i in obj) {....}`, a better way to pose this problem would be to show these attempts, how they are failing, and ask for specific assistance. – Alexander Nied Dec 28 '18 at 03:28

1 Answers1

2

You're basically asking how to flatten a nested object, with the keys representing the nested path. Here's a little recursive function that does just that:

const flatten = (o, pre) => Object.entries(o).reduce((a, [k, v]) => (
  key = pre ? `${pre}_${k}`: k,
  {
    ...a,
    ...Object.getPrototypeOf(v) !== Object.prototype ? {[key]: v} : flatten(v, key)
  }), {});

Full snippet:

const o = {
    "title": "aa",
    "desc": ["i", "j", "k"],
    "cnt": {
        "head": "bb",
        "main": {
            "num1": {
                "time1": "mm",
                "time2": "kk"
            },
            "num2": "dd"
        }
    }
};

const flatten = (o, pre) => Object.entries(o).reduce((a, [k, v]) => (
  key = pre ? `${pre}_${k}`: k,
  {
    ...a,
    ...Object.getPrototypeOf(v) !== Object.prototype ? {[key]: v} : flatten(v, key)
  }), {});

console.log(flatten(o));
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
  • it solved my problem, thank you very much! Hope this can help some other guys too. – hijack Jan 04 '19 at 07:02
  • 1
    Perfect for my application. Thank you. There are a lot of questions and answers regarding flattening JSON out there and this answer is by far the most useful. – Shanerk Sep 05 '22 at 19:29