1

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

SmartDev
  • 481
  • 3
  • 11
  • 30

3 Answers3

1

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;
}, {});
Marlon Bernardes
  • 13,265
  • 7
  • 37
  • 44
1

Try this code:

var myparam = {};

for (var i = 0; i < usrPrefs.length; i++) {
    myparam[usrPrefs[i].name] = usrPrefs[i].value;
}
Olim Saidov
  • 2,796
  • 1
  • 25
  • 32
1

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;
 }; 
Will
  • 221
  • 3
  • 12