I have an object like this:
{
user[id]: 1,
user[name]: 'Lorem',
money: '15.00'
}
And I want this:
{
user: {
id: 1,
name: 'Lorem',
},
money: '15.00'
}
How can I achieve this?
nickhar
21.1k12 gold badges64 silver badges77 bronze badges
asked Jul 30, 2012 at 1:42
Rafael Motta
2,5802 gold badges20 silver badges18 bronze badges
-
Is the first JSON? Can you make a jsfiddle.net demo of your problem?Jared Farrish– Jared Farrish2012年07月30日 01:47:19 +00:00Commented Jul 30, 2012 at 1:47
-
I want to transform the input values and keys direct in a JSON...jsfiddle.net/MFWLH/1 And vice-versa. Sometimes I have the json and want to set in the inputs..Rafael Motta– Rafael Motta2012年07月30日 02:03:10 +00:00Commented Jul 30, 2012 at 2:03
1 Answer 1
Something like this
var x = {
"user[id]": 1,
"user[name]": 'Lorem',
"money": '15.00'
}
var y = {};
for (var i in x){
var z = /(.+)\[(.+)\]/g.exec(i);
if (z){
if (!y.hasOwnProperty(z[1])){
y[z[1]] = {};
}
y[z[1]][z[2]] = x[i];
}
else{
y[i] = x[i];
}
}
answered Jul 30, 2012 at 2:03
Musa
97.9k17 gold badges123 silver badges144 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js