简体   繁体   中英

Convert JSON to array of objects with custom keys and values

I receive from the server a JSON string:

{0:["aNumber","aText","anID"],1:["aNumber","aText","anID"].. .

I must elaborate this string so that:

  1. aNumber is concatenated with client side strings (say, it becomes "http://www.myurl.com/aNumber.jpg");
  2. aNumber becomes the value of url in array of objects;
  3. aText becomes the value of caption in the same array;
  4. anID becomes the value of id in the same array;

    [{url:"http://www.myurl.com/aNumber.jpg",caption:"aText",id:"anID}.{url:"http://www.myurl.com/aNumber.jpg",caption:"aText",id:"anID"}...

I perfectly know how to do this, but I wanted to know if anyone knows if is possible to do the same thing avoiding a loop: the JSON is really huge (more than 10000 items) in a mobile context, so I was hoping in something magic to improve performances.

Try looping through 10,000 items in a mobile context. Then try 100,000 and then 1,000,000. You'll probably see that looping is not the greatest performance bottleneck.

You can't really do that, here the best solution is to convert one specific child array in the object only when you need it.

Anyway, the loop is not so long to execute, the longest is the parsing JSON String > Object.

For your loop, I would have made something like:

obj=JSON.parse({0:["aNumber","aText","anID"],1:["aNumber","aText","anID"]});
arr=[];
for(i in obj){
  o=obj[i]; // improve performances on big objects
  arr.push({url: "http://www.myurl.com/"+ o[0] + ".jpg", caption:o[1], id:o[2]});
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM