Convert array of JSON object strings to array of JS objects

后端 未结 3 687
悲&欢浪女
悲&欢浪女 2020-12-08 05:23

I would like to convert an array of JSON String to array of JSON object without looping through each item and parse it using JSON.parse.

Example:

var         


        
3条回答
  •  自闭症患者
    2020-12-08 05:56

    If you have a JS array of JSON objects:

    var s=['{"Select":"11","PhotoCount":"12"}','{"Select":"21","PhotoCount":"22"}'];
    

    and you want an array of objects:

    // JavaScript array of JavaScript objects
    var objs = s.map(JSON.parse);
    
    // ...or for older browsers
    var objs=[];
    for (var i=s.length;i--;) objs[i]=JSON.parse(s[i]);
    
    // ...or for maximum speed:
    var objs = JSON.parse('['+s.join(',')+']');
    

    See the speed tests for browser comparisons.


    If you have a single JSON string representing an array of objects:

    var s='[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';
    

    and you want an array of objects:

    // JavaScript array of JavaScript objects
    var objs = JSON.parse(s);
    

    If you have an array of objects:

    // A JavaScript array of JavaScript objects
    var s = [{"Select":"11", "PhotoCount":"12"},{"Select":"21", "PhotoCount":"22"}];
    

    …and you want JSON representation for it, then:

    // JSON string representing an array of objects
    var json = JSON.stringify(s);
    

    …or if you want a JavaScript array of JSON strings, then:

    // JavaScript array of strings (that are each a JSON object)
    var jsons = s.map(JSON.stringify);
    
    // ...or for older browsers
    var jsons=[];
    for (var i=s.length;i--;) jsons[i]=JSON.stringify(s[i]);
    

提交回复
热议问题