-4

I need to parse Json response

{
   "product": "office",
   "info": 
   {
      "brand": 
      [
        "1brand"
      ],
      "detail": 
      {
        "number": 
        {
            "min": 1,
            "max": 5
         },
       }
   }
};

to object with dotted strings keys

{
    "product" : "office",
    "info.brand" : ["1brand"],
    "info.detail.number.min" : 1,
    "info.detail.number.max" : 5
}

Number of nested and adjacent objects isn't known. Solution should be function with one parameter - response object and return with new object (with dotted strings keys).

Filip
  • 143
  • 1
  • 8
  • So what did you try yet? – Phiter Aug 23 '18 at 19:45
  • `solution should be...` you din't try anything and it seems you're ordering us to deliver the code. and -1 for this. – Bhojendra Rauniyar Aug 23 '18 at 19:48
  • Possible duplicate of [Converting Nested json into dot notation json](https://stackoverflow.com/questions/45349516/converting-nested-json-into-dot-notation-json) – JSTL Aug 23 '18 at 19:49
  • I tried some algorthm with Object.key and found some solutions with more parameters but nothing seems to good fit for my problems. @BhojendraRauniyar – Filip Aug 23 '18 at 20:07

2 Answers2

1

You could take a recursice approach for each level of nested objects and collect keys and use them for the last found value in a new object.

function flatKeys(object) {

    function iter(part, keys) {
        Object.keys(part).forEach(function (k) {
            var allKeys = keys.concat(k);
            if (part[k] && !Array.isArray(part[k]) && typeof part[k] === 'object') {
                return iter(part[k], allKeys);
            }
            flat[allKeys.join('.')] = part[k];
        });
    }

    var flat = {};
    iter(object, []);
    return flat;
}

var object = { product: "office", info: { brand: ["1brand"], detail: { number: { min: 1, max: 5 } } } };

console.log(flatKeys(object));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Oh, that is great solution. I was trying almost everything with Object.key but I can not build the right recursive algorthm. Thank you – Filip Aug 23 '18 at 20:04
0

You could create recursive function with reduce method.

let data = {"product":"office","info":{"brand":["1brand"],"detail":{"number":{"min":1,"max":5}}}}

function parse(input, res = {}, prev = '') {
  return Object.keys(input).reduce((r, e) => {
    let key = prev + (prev && '.') + e, val = input[e]
    if (typeof val == "object" && !Array.isArray(val)) parse(val, res, key)
    else r[key] = input[e]
    return r;
  }, res)
}

let result = parse(data)
console.log(result)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176