I have below json parse data and i am trying to convert it to javascript object
usrPrefs
[Object { name="mystocks", value="500400,532500,500180,500312,500325"},
Object { name="mystocksname", value="Tata Power,Maruti Suzuki...NGC,Reliance Industries"},
Object { name="refresh_secs", value="600"}]
i am trying to convert this to something like below
myparam = {
mystocks:500400,532500,500180,500312,500325,
mystocksname:Tata Power,Maruti Suzuki...NGC,Reliance Industries
....
}
how i can do that in javascript something like using loop or any build in function, i started learning javascript and i am stuck here...
thank you in advance.
Regards, Mona
You could use the reduce
function in order to achieve that:
var myparam = usrPrefs.reduce(function(a, b){
a[b.name] = b.value;
return a;
}, {});
Try this code:
var myparam = {};
for (var i = 0; i < usrPrefs.length; i++) {
myparam[usrPrefs[i].name] = usrPrefs[i].value;
}
You might choose to use array instead of string, its more convenient for you to use
function toMap(usrPrefs){
var result = {};
for(var i = 0 ; i < usrPrefs.length ; i++){
var obj = usrPrefs[i];
var array = obj.value.split(',').trim();
result[obj.name] = array;
}
return result;
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.