-1

我一直在努力构建一个 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"} ] 
 }

如何在索引变量中输入值?

谢谢你的帮助

4

2 回答 2

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;

    }
于 2012-10-14T09:48:19.423 回答
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"');
}
于 2012-10-14T10:26:45.833 回答