简体   繁体   中英

Javascript - How to Flatten a nested JSON object

I have a Nested JSON input as shown below which I want to flatten into expected output. Key won't be always the same eg: u_summary, created_date, u_product ie there could be even more keys.

Any help?

JSON Nested input:

var jsonUnflattenInput = 
    [
        
        {
            "u_summary": {
                "display_value": "Please check the data and set the company accordingly if everything is fine.",
                "value": "Please check the data."
            },
            "created_date": {
                "display_value": "2022-06-18 11:45:00",
                "value": "2022-05-29 21:42:01"
            },
            "u_product": {
                "display_value": "Undefined",
                "value": "2345567"
            }
        },
        {
            "u_summary": {
                "display_value": "╓ tool v14.3",
                "value": "14.3"
                },
            "created_date": {
                "display_value": "2022-03-18 11:45:00",
                "value": "2022-02-29 21:42:01"
            },
            "u_product": {
                "display_value": "test_product",
                "value": "1367"
            }
        }
    ]

Expected JSON Output:

[
    {
        "dv_u_summary": "Please check the data and set the company accordingly if everything is fine.",
        "u_summary": "Please check the data.",
        "dv_created_date": "2022-06-18 11:45:00",
        "created_date": "2022-05-29 21:42:01",
        "dv_u_product": "Undefined",
        "u_product": "2345567"
    },
    {
        "dv_u_summary": "╓ tool v14.3",
        "u_summary": "14.3",
        "dv_created_date": "2022-03-18 11:45:00",
        "created_date": "2022-02-29 21:42:01",
        "dv_u_product": "test_product",
        "u_product": "1367"
    }
]

I tried the below code after referring to some blogs, but couldn't get the expected output.

function flatten(json, flattened, str_key) {
                for (var key in json) {
                  if (json.hasOwnProperty(key)) {
                    if (json[key] instanceof Object && json[key] != "") {
                      flatten(json[key], flattened, str_key + "." + key);
                    } else {
                      flattened[str_key + "." + key] = json[key];
                    }
                  }
                }
            }

        var flattened = {};
         
        flatten(jsonUnflattenInput, flattened, "");
        

        for (var key in flattened){
          console.log(key + ": " + flattened[key]);
        }

 function flatten(json) { var newJSON = []; for (var i = 0; i < json.length; i++) { var obj = {}; for (var key in json[i]) { if (json[i].hasOwnProperty(key)) { obj['dv_' + key] = json[i][key]['display_value']; obj[key] = json[i][key]['value']; } } newJSON.push(obj); } return newJSON; } var jsonUnflattenInput = [ { "u_summary": { "display_value": "Please check the data and set the company accordingly if everything is fine.", "value": "Please check the data." }, "created_date": { "display_value": "2022-06-18 11:45:00", "value": "2022-05-29 21:42:01" }, "u_product": { "display_value": "Undefined", "value": "2345567" } }, { "u_summary": { "display_value": "╓ tool v14.3", "value": "14.3" }, "created_date": { "display_value": "2022-03-18 11:45:00", "value": "2022-02-29 21:42:01" }, "u_product": { "display_value": "test_product", "value": "1367" } } ] console.log(flatten(jsonUnflattenInput))

This should work for the provided example data.

This can be done as follows:

jsonUnflattenInput.map(o =>
  Object.keys(o).reduce((acc, k) => {
    acc['dv_' + k] = o[k].display_value;
    acc[k] = o[k].value;
    return acc;
  }, {})
);

Please take a look at below runnable code and see how it works.

 var jsonUnflattenInput = [{ "u_summary": { "display_value": "Please check the data and set the company accordingly if everything is fine.", "value": "Please check the data." }, "created_date": { "display_value": "2022-06-18 11:45:00", "value": "2022-05-29 21:42:01" }, "u_product": { "display_value": "Undefined", "value": "2345567" } }, { "u_summary": { "display_value": "╓ tool v14.3", "value": "14.3" }, "created_date": { "display_value": "2022-03-18 11:45:00", "value": "2022-02-29 21:42:01" }, "u_product": { "display_value": "test_product", "value": "1367" } } ]; const result = jsonUnflattenInput.map(o => Object.keys(o).reduce((acc, k) => { acc['dv_' + k] = o[k].display_value; acc[k] = o[k].value; return acc; }, {}) ); console.log(result);

You could take an array for wanted keys and functions for values and map the entries for new objects.

 const structure = [ ['dv_u_summary', o => o.u_summary.display_value], ['u_summary', o => o.u_summary.value], ['dv_created_date', o => o.created_date.display_value], ['created_date', o => o.created_date.value], ['dv_u_product', o => o.u_product.display_value], ['u_product', o => o.u_product.value] ], data = [{ u_summary: { display_value: "Please check the data and set the company accordingly if everything is fine.", value: "Please check the data." }, created_date: { display_value: "2022-06-18 11:45:00", value: "2022-05-29 21:42:01" }, u_product: { display_value: "Undefined", value: "2345567" } }, { u_summary: { display_value: "╓ tool v14.3", value: "14.3" }, created_date: { display_value: "2022-03-18 11:45:00", value: "2022-02-29 21:42:01" }, u_product: { display_value: "test_product", value: "1367" } }], result = data.map(o => Object.fromEntries(structure.map(([k, fn]) => [k, fn(o)]))); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM