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

3
  • possible duplicate of Safely turning a JSON string into an object Commented Jul 30, 2014 at 16:36
  • And var myArray = []; myArray = JSON.parse(usrPrefs); doesn't work? Commented Jul 30, 2014 at 16:40
  • As all answers are correct. i have voted all. But accepted which one suits my need. Thank you very much everyone. Commented Aug 3, 2014 at 14:03

3 Answers 3

0

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;
}, {});
Sign up to request clarification or add additional context in comments.

2 Comments

This will return an array of objects each with a single key and value, which is not what is wanted.
@Stuart True! I'm gonna fix that.
0

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;
 }; 

Comments

0

Try this code:

var myparam = {};

for (var i = 0; i < usrPrefs.length; i++) {
    myparam[usrPrefs[i].name] = usrPrefs[i].value;
}

2 Comments

Why are you skipping the last element of the array? You need to change i < usrPrefs.length - 1 to i < usrPrefs.length
My bad, sorry. Fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.