【问题标题】:Array combination of associative key and number in javascriptjavascript中关联键和数字的数组组合
【发布时间】:2012-11-02 13:23:08
【问题描述】:

简而言之,我已经开始我的问题了,

我只是读取json文件,

 [{"FirstCategory":"Bath","SecondCategory":"Bath Accessories","ThirdCategory":""}, {"FirstCategory":"Bath","SecondCategory":"Faucets","ThirdCategory":""},{"FirstCategory":"Bath","SecondCategory":"Fixtures","ThirdCategory":""},{"FirstCategory":"Bath","SecondCategory":"Vanities","ThirdCategory":""},{"FirstCategory":"Building Materials","SecondCategory":"Concrete","ThirdCategory":""},{"FirstCategory":"Building Materials","SecondCategory":"Fencing","ThirdCategory":""},{"FirstCategory":"Building Materials","SecondCategory":"Gypsum","ThirdCategory":""},{"FirstCategory":"Building Materials","SecondCategory":"Insulation","ThirdCategory":""},{"FirstCategory":"Building Materials","SecondCategory":"Insulssdation","ThirdCategory":""}]

并试图转换成数组

Array
(
  [Bath] => Array
    (
        [Bath Accessories] => Array
            (
                [0] => test
            )

        [Faucets] => Array
            (
                [0] => test1
                [1] => test2
            )

    )

)//sorry i have used PHP for simple formatting the array.

我花了很多时间在这件事上,但我无法成功,请帮助我。

 My javascript code : (not working.)

 var FirstCategory = [];
 var SecondCategory = [];
 var ThirdCategory = [];


 $.getJSON('tree.json', function(data) {

var dataObj = new Array();
$.each(data,function(i){
    dataObj[data[i].FirstCategory] = new Array();

    if([data[i].SecondCategory] in dataObj[data[i].FirstCategory])
        dataObj[data[i].FirstCategory][data[i].SecondCategory] = data[i].SecondCategory;
    else
        dataObj[data[i].FirstCategory][data[i].SecondCategory] = new Array();

    dataObj[data[i].FirstCategory][data[i].SecondCategory][data[i].ThirdCategory] = new Array();

});

 console.log(dataObj);

/*
$.each(data,function(i){

    if (FirstCategory == '') {
        FirstCategory.push(data[i].FirstCategory);
    }
    else
    {
        if(!FirstCategory.contains(data[i].FirstCategory))
        {
            //root
            FirstCategory.push(data[i].FirstCategory);
        }
        else
        {
            //------- second level category -------//
            if (SecondCategory == '') {
                SecondCategory.push(data[i].SecondCategory);
            }
            else
            {
                if(!SecondCategory.contains(data[i].SecondCategory))
                {
                    SecondCategory.push(data[i].SecondCategory);
                }
                else
                {
                    ThirdCategory.push(data[i].ThirdCategory);
                }
            }

        }
    }   

});
*/

});


Array.prototype.contains = function(obj) {
  var i = this.length;
  while (i--) {
        if (this[i] == obj) {
         return true;
      }
  }
   return false;
}

提前致谢。

【问题讨论】:

  • 您的 json 不在该表单上是否有原因?如果不是,我建议改为更改后端。
  • 首先你应该意识到,在 JavaScript 中,你创建的是一个普通的对象,而不是一个数组。
  • 你从哪里得到这些 testtest1test2 值?

标签: javascript jquery arrays json multidimensional-array


【解决方案1】:

请注意Javascript has no "associative arrays"

更多编程方式:

var levels = ["FirstCategory", "SecondCategory", "ThirdCategory"]; // possibly more
var dataObj = {}; // an empty object
for (var i=0; i<data.length; i++) {
    var cur = dataObj;
    for (var j=0; j<levels.length; j++) {
        var key = data[i][levels[j]];
        if (!key) // empty
            break;
        if (key in cur)
            cur = cur[key];
        else
            cur = cur[key] = {};
    }
}

结果 (dataObj) 用于您的示例输入,格式为 JSON:

{
    "Bath": {
        "Bath Accessories": {},
        "Faucets": {},
        "Fixtures": {},
        "Vanities": {}
    },
    "Building Materials": {
        "Concrete": {},
        "Fencing": {},
        "Gypsum": {},
        "Insulation": {},
        "Insulssdation": {}
    }
}

【讨论】:

    【解决方案2】:

    这可能会奏效:

    input = [{"FirstCategory":"Bath","SecondCategory":"Bath     Accessories","ThirdCategory":""}, {"FirstCategory":"Bath","SecondCategory":"Faucets","ThirdCategory":""},{"FirstCategory":"Bath","SecondCategory":"Fixtures","ThirdCategory":""},{"FirstCategory":"Bath","SecondCategory":"Vanities","ThirdCategory":""},{"FirstCategory":"Building Materials","SecondCategory":"Concrete","ThirdCategory":""},{"FirstCategory":"Building Materials","SecondCategory":"Fencing","ThirdCategory":""},{"FirstCategory":"Building Materials","SecondCategory":"Gypsum","ThirdCategory":""},{"FirstCategory":"Building Materials","SecondCategory":"Insulation","ThirdCategory":""},{"FirstCategory":"Building Materials","SecondCategory":"Insulssdation","ThirdCategory":""}];
    
    function reducer (prev, val) {
        v1 = val["FirstCategory"]
        v2 = val["SecondCategory"]
        if (!(v1 in prev)) { prev[v1] = {}; }
        if (!(v2 in prev[v1])) { prev[v1][v2] = [];}
        prev[v1][v2].push(val["ThirdCategory"]);
        return prev;
    }
    
    output = input.reduce(reducer, {});
    
    console.log(input);
    console.log(output);
    

    输出:

    { Bath: 
       { 'Bath Accessories': [ '' ],
         Faucets: [ '' ],
         Fixtures: [ '' ],
         Vanities: [ '' ] },
      'Building Materials': 
       { Concrete: [ '' ],
         Fencing: [ '' ],
         Gypsum: [ '' ],
         Insulation: [ '' ],
         Insulssdation: [ '' ] } }
    

    【讨论】:

    • 非常好的解决方案....但是要小心! Array.reduce() 是 ECMAScript 5 的补充。最新的 Chrome、FF、Opera、Safari 和 IE9 都可以,但 IE6/7/8 需要解决方法脚本。阅读所有相关信息 here
    • @RudolfMühlbauer : 谢谢老兄:)
    【解决方案3】:

    试试这个:

    var formattedData = {};
    $.each(data, function(i, item) {
        if(!formattedData[item.FirstCategory]) {
            formattedData[item.FirstCategory] = {};
        }
        if(!formattedData[item.FirstCategory][item.SecondCategory]) {
            formattedData[item.FirstCategory][item.SecondCategory] = [];
        }
        formattedData[item.FirstCategory][item.SecondCategory].push(item.ThirdCategory);
    });
    

    生成的对象将具有以下结构:

    var formattedData = {
        'Bath': {
            'Bath Accessories': [
                'Non-slip Bath Mat'
            ],
            'Faucets': [
                'Brass Fawcet (Pair)',
                'Chrome Fawcet (Pair)',
                'Gold Fawcet (Monoblock)'
            ],
            'Fixtures': [
                'xxx',
                'yyy',
                'zzz'
            ],
            //etc.
            //etc.
        }
    };
    

    DEMO

    【讨论】:

      猜你喜欢
      • 2016-02-17
      • 1970-01-01
      • 1970-01-01
      • 2012-02-25
      • 2011-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多