Easiest way to interate over a complex JSON object via Javascript

后端 未结 7 1862
生来不讨喜
生来不讨喜 2020-12-21 07:19

I\'m consuming JSON data that has a bit of a weird structure for example:

{
    \"RESULT\": 
    {
        \"COLUMNS\": [\"ID\",\"name\",\"ENABLED\",\"perms\         


        
7条回答
  •  醉梦人生
    2020-12-21 08:11

    you can use underscore Array functions for this task

    http://underscorejs.org/#arrays

    uusing the object function would be helpful http://underscorejs.org/#object

    from the documentation : _.object(list, [values]) Converts arrays into objects. Pass either a single list of [key, value] pairs, or a list of keys, and a list of values ..the example:

    _.object(['moe', 'larry', 'curly'], [30, 40, 50]);
     => {moe: 30, larry: 40, curly: 50}
    

    here is the JSfiddle with the solution http://jsfiddle.net/rayweb_on/kxR88/1/

    and the code looks like this for this specific scenario.

     var plain = {
    "RESULT": 
    {
        "COLUMNS": ["ID","name","ENABLED","perms","vcenabled","vcvalue","checkenabled","checkvalue","indxenabled","indxvalue"],
        "DATA": [
                    [7,"Site-A", 1, "1,2", 1, 1, 1, 0, 0, 0],
                    [15,"Site-B", 1, "1,2,3,4", 1, 1, 1, 0, 0, 0]
        ]
    },
    "ERROR": 0
    },
    
    formatted = [];
    
    _.each(plain.RESULT.DATA, function(value) {
        var tmp = {};
         tmp = _.object(plain.RESULT.COLUMNS,value)
        formatted.push(tmp);
    });
    
     console.log(formatted);
    

提交回复
热议问题