构造Json数组时遇到麻烦

时间:2012-10-14 09:24:00

标签: javascript json

我一直在努力构建一个json阵列几个小时,但没有任何成功。对于有json经验的人来说,这对他来说是一块蛋糕。

所以我想构建一个像这样的json数组:

 { 
    "M" : [ {id:"58893_1_M", value:"Ontario", imageFile:"58893_1.jpg"} ] ,
    "L" : [ {id:"58893_1_L", value:"Ontario", imageFile:"58893_1.jpg"} ] , 
    "XL" : [ {id:"58893_1_XL", value:"Ontario", imageFile:"58893_1.jpg"} ] 
 }

以下是代码:

 var totalObjects = new Array();

 for (i = 0; i < roomQuotes.length; i++) {

        var selectedClothe = {
            index: []
        };

        var clotheId = some value;
        var clotheQuantity = some value;
        var clotheImage =some value;

        selectedClothe.index.push({ "id": clotheId , "value": clotheQuantity , "imageFile": clotheImage });

        totalObjects.push(selectedClothe);

    }

但我有这个输出

 { 
    "index" : [ {id:"58893_1_M", value:"Ontario", imageFile:"58893_1.jpg"} ] ,
    "index" : [ {id:"58893_1_L", value:"Ontario", imageFile:"58893_1.jpg"} ] , 
    "index" : [ {id:"58893_1_XL", value:"Ontario", imageFile:"58893_1.jpg"} ] 
 }

如何在索引变量中添加值?

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

尝试:

var totalObjects = {};

 for (i = 0; i < roomQuotes.length; i++) {

        var selectedClothe = [];

        var clotheId = some value;
        var clotheQuantity = some value;
        var clotheImage =some value;

        selectedClothe.push({ "id": clotheId , "value": clotheQuantity , "imageFile": clotheImage });

        totalObjects.[clotheId.substr(clotheId.lastIndexOf('_') +1)] = selectedClothe;

    }

答案 1 :(得分:0)

使用它。假设在_字符后面的ID名称是衣服大小。

var totalObjects = {}; //selection object

for (i = 0; i < roomQuotes.length; i++) {

    var clotheId = some value;
    var clotheQuantity = some value;
    var clotheImage = some value;

    var clotheSize = clotheId.substr(clotheId.lastIndexOf('_')+1);
    if (typeof(totalObjects[clotheSize]) == 'undefined') {
        //clothe size array not yet exist. create it
        totalObjects[clotheSize] = []; //clothe size array
    }

    totalObjects[clotheSize].push({ "id": clotheId , "value": clotheQuantity , "imageFile": clotheImage });
}
//note: there will be no "totalObjects.XL" if there's no selected clothe of "XL" size

//example: list selected clothe sizes
//see web browser's Error Console for console.log result
var clotheSizes = Object.keys(totalObjects); //clothe size code array
console.log('Selected clothe sizes: '+clotheSizes.join(', '));
//shows e.g.: "M, L, XL" or "" if no selection

//example: get first selected clothe ID of first clothe size selection
if (clotheSize.length > 0) {
    var clothSizeSelections = totalObjects[clotheSizes[0]];
    console.log('First selected clothe ID: '+clothSizeSelections[0].id);
} else {
    console.log('No selection');
}

//example: is "M" clothe size has selection?
if (typeof(totalObjects.M) != 'undefined') {
    console.log(totalObjects.M.length+' selections for clothe size "M"');
} else {
    console.log('No selection for clothe size "M"');
}