0

I have this javascript object format

{
  "draw": "",
  "columns": [
    {
      "data": "userid",
      "name": "",
      "searchable": true,
      "search": {
        "value": "",
        "regex": false
      }
    }
  ]
}

and what I need to do is convert it into single dimension object like

{ 
 "draw" : "",
 "columns[data]": "userid",
 "columns[name]": "",
 "columns[searchable]": "true",
 "columns[searchable][value]": "",
 "columns[searchable][regex]":"true"
}

the primary object can be multiple layers deep and contains objects as well as arrays.

any ideas suggestions much appreciated as JS is not my forte.

3
  • 5
    Shouldn't the result be columns[0][searchable][regex]: instead of columns[searchable][regex]? Commented Dec 6, 2019 at 8:07
  • 2
    isn't it an XY problem? why do you want to do this particular thing? It seems to me like it might be an attempted solution to some other problem you are not telling us about. Commented Dec 6, 2019 at 8:13
  • 1
    what do you do after getting an object with only one level? and why do you don't have an index for the array? how do you know, that the original data comes from an array? Commented Dec 6, 2019 at 8:43

2 Answers 2

1

I would use a recursive function that accepts a property of the original and the path to that object. If the property is not an object, then add the value to the path, if it is, then iterate through its properties and call the recursive function.

var object = {
  "draw": "",
  "columns": [{
    "data": "userid",
    "name": "",
    "searchable": true,
    "search": {
      "value": "",
      "regex": false
    }
  }]
};

console.log(flatten(object));

function flatten(object) {
  var result = {};
  innerFlatten(object, "");
  return result;

  function innerFlatten(object, path) {
    if (typeof object !== "object" || object === null || object instanceof Date) return result[path] = object;
    if (!Object.keys(object).length) return result[path] = object;
    for (var key in object) {
      innerFlatten(object[key], path ? (path + "[" + key + "]") : key);
    }
  }
}

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I used some of your logic and this stackoverflow reference stackoverflow.com/questions/54896928/…. Created another version of this answer here pastebin.com/Xq7RHiTw
-1

I think you want to remove array from columns and set to 0 index value

let test = {
  "draw": "",
  "columns": [
    {
      "data": "userid",
      "name": "",
      "searchable": true,
      "search": {
        "value": "",
        "regex": false
      }
    }
   ]
}

test.columns = test.columns[0]

console.log(test)

2 Comments

This is not what OP wants
@ThumChoonTat Okay I want to delete my answer though my account is guest so I cant

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.