For example i have object js
data = {"dt1_a": 20, "dt1_b": 30, "dt2_a": 40, "dt2_b": 50}
I want convert data to
data1 = {"dt1": {"a": 20, "b": 30}, "dt2": {"a": 40, "b": 50}}
Please suggest a specific solution.
Try something like
var data1 = {};
$.each(data, function (key, value) {
var parts = key.split('_'),
p1 = parts[0];
if (!data1[p1]) {
data1[p1] = {};
}
data1[p1][parts[1]] = value;
})
console.log(data1)
Demo: Fiddle
Grab the object keys and loop through them, then apply the correct properties to the new object.
data = {"dt1_a": 20, "dt1_b": 30, "dt2_a": 40, "dt2_b": 50};
var data1 = {};
Object.keys(data).forEach(function(key){
var keySplit = key.split("_");
//create dt1, dt2 properties if they do not exist yet
data1[keySplit[0]] = data1[keySplit[0]] || {};
data1[keySplit[0]][keySplit[1]] = data[key]
});
Note this is reliant on the browser supporting forEach if the browser does not have it a polyfill can be used
You could also use for..in as Joseph Marikle mentions in the comments, which is also more compatible
for(key in data){
var keySplit = key.split("_");
//create dt1, dt2 properties if they do not exist yet
data1[keySplit[0]] = data1[keySplit[0]] || {};
data1[keySplit[0]][keySplit[1]] = data[key]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With