Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Recursion for creating a JSON object

Tags:

javascript

needing some advice on how to do this properly recursively.

Basically what I'm doing, is entering in a bunch of text and it returns it as JSON.

For example:

The text:

q
b
name:rawr

Returns:

[
  "q",
  "b",
  {
    "name": "rawr"
  }
]

And the following input:

q
b
name:rawr:awesome

Would return (output format is not important):

[
  "q",
  "b",
  {
    "name": {
        "rawr": "awesome"
    }
  }
]

How can I modify the following code to allow a recursive way to have objects in objects.

var jsonify = function(input){
  var listItems = input, myArray = [], end = [], i, item;

  var items = listItems.split('\r\n');

  // Loop through all the items
  for(i = 0; i < items.length; i++){

    item = items[i].split(':');

    // If there is a value, then split it to create an object
    if(item[1] !== undefined){
      var obj = {};
      obj[item[0]] = item[1];  
      end.push(obj);
    }
    else{
      end.push(item[0]);
    }
  }

  // return the results
  return end;
};
like image 819
Menztrual Avatar asked Mar 13 '26 00:03

Menztrual


1 Answers

I don't think recursion is the right approach here, a loop could do that as well:

var itemparts = items[i].split(':');

var value = itemparts.pop();
while (itemparts.length) {
    var obj = {};
    obj[itemparts.pop()] = value;
    value = obj;
}
end.push(value);

Of course, as recursion and loops have equivalent might, you can do the same with a recursive function:

function recurse(parts) {
    if (parts.length == 1)
        return parts[0];
    // else
    var obj = {};
    obj[parts.shift()] = recurse(parts);
    return obj;
}
end.push(recurse(items[i].split(':')));
like image 60
Bergi Avatar answered Mar 14 '26 14:03

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!