简体   繁体   English

具有对象数组的Javascript对象

[英]Javascript Object with Array of objects

I'm wondering if it is possible to create a javascript map with array of objects as content. 我想知道是否可以创建一个以对象数组为内容的javascript映射。

My code is as follows: 我的代码如下:

//Object that replicates a Map
var itemRcptMap = {};

//Receipt Object Holder
var objReceipt = {
     id     : '',
     item   : '',
     qty    : '',
     lotNo  : ''
};

//Iterate an object result w/c is not shown in the example 
for (var i in itemRcptResult)
{
    var id = itemRcptResult[i].id;

    if(!itemRcptMap[id]){
        itemRcptMap[id] = new Array();
    }
    objReceipt.id    = arItemRcptResult[i]id;
    objReceipt.item  = arItemRcptResult[i].items;
    objReceipt.qty   = arItemRcptResult[i].quantity;
    objReceipt.lotNo = arItemRcptResult[i].test;
    itemRcptMap[id] = itemRcptMap[id].push(objReceipt);
}

I'm having the following error 我遇到以下错误

Cannot find function push in object 1.

How can I correct this? 我该如何纠正?

THank you. 谢谢。

Code Simplification: 代码简化:

var itemRcptMap = {};

//Receipt Object Holder
var objReceipt = {
     id     : '',
     item   : '',
     qty    : '',
     lotNo  : ''
};

var id = 5555;
    if(!itemRcptMap[id]){
        itemRcptMap[id] = new Array();
    }
    objReceipt.id    = 1;
    objReceipt.item  = 2;
    objReceipt.qty   = 3;
    objReceipt.lotNo = 4;
    itemRcptMap[id].push(objReceipt);

 //Gets the object with Key 5555
var x = itemRcptMap[5555];  
alert(x.id)

When you push to an array, the return value will be the new length of the array (which you are reassigning back to the actual array) so in the next iteration you are not pushing it to the array instead you are trying to access push method of numeric value( number does not have a push method.). 当您push送到数组时,返回值将是该数组的新长度(您将重新分配给实际数组),因此在下一次迭代中,您不会将其推送到数组,而是尝试访问push方法数值( number没有推送方法)。 Push mutates the source array so just do:- 推变异源数组,所以只需:-

itemRcptMap[id].push(objReceipt);

You might want to move objReceipt declaration inside of the loop. 您可能想将objReceipt声明移入循环内。 Other wise you will end up getting the same object in all the arrays. 否则,您将最终在所有数组中得到相同的对象。

Based on your comments, possibly you are looking to create a flat map with id (not duplicated) you could do. 根据您的评论,可能您希望创建一个ID为ID(不可重复)的平面地图。

//Object that replicates a Map
var itemRcptMap = {};

for (var i=0, l=itemRcptResult.length; i<l; i++){ 
    var id = itemRcptResult[i].id;
    itemRcptMap[id] = itemRcptResult[i];
}

Note if itemRcptResult is an array then dont use for..in loop 注意,如果itemRcptResult是一个数组,则不要使用for..in循环

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM