سؤال

I'm trying to build a quick JavaScript function that will receive a JavaScript object like this:

{
    "sample[one]": "value 1",
    "sample[hard][damn_you[0]]": "this 1",
    "sample[hard][damn_you[1]]": "this 2"
}

And transform it to something like this:

{
    "[sample][one]": "value 1",
    "[sample][hard][damn_you][0]": "this 1",
    "[sample][hard][damn_you][1]": "this 2"
}

Subtle but big difference. I've already worked out the first part, which involves wrapping the first part of the text in a square bracket, but when it comes to take out the nested square brackets and putting them out, I'm at a loss. I've been trying for quite some time without success. Here's what I have so far:

var data = {
        "sample[one]": "value 1",
        "sample[hard][damn_you[0]]": "this 1",
        "sample[hard][damn_you[1]]": "this 2"
    },
    subset = /^([a-z0-9-_]+?)\[/i;

for (var key in data) {
    if (subset.test(key)) {
        data[key.replace(subset,'[$1][')] = data[key];
    } else {
        data[key.replace(/^(.+)$/,'[$1]')] = data[key];
    }
    delete data[key];
}

Which outputs this:

{
    "[sample][one]": "value 1",
    "[sample][hard][damn_you[0]]": "this 1",
    "[sample][hard][damn_you[1]]": "this 2"
}

But am at a loss when it comes to extracting those nested square brackets. Any ideas?

هل كانت مفيدة؟

المحلول

Essentially, you're looking for every consecutive set of characters that are not square brackets. It doesn't matter what order the brackets are in. So you could quite easily do something like this:

key = "["
    +key.replace(/]/g,'[') // replace close brackets with open ones
                           // (to make them the same symbol)
    .replace(/\[+$/,'')    // trim off brackets at the end of the string
    .replace(/\[+/g,"][")  // replace brackets with "][" (separating the words)
    +"]";

So for example sample[hard][damn_you[0]] goes through these steps:

  • sample[hard][damn_you[0]]
  • sample[hard[[damn_you[0[[
  • sample[hard[[damn_you[0
  • [sample][hard][damn_you][0]
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top