newbie
newbie

Reputation: 14950

Javascript Object with Array of objects

I'm wondering if it is possible to create a javascript map with array of objects as content.

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)

Upvotes: 1

Views: 2866

Answers (1)

PSL
PSL

Reputation: 123739

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 mutates the source array so just do:-

itemRcptMap[id].push(objReceipt);

You might want to move objReceipt declaration inside of the loop. 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.

//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

Upvotes: 4

Related Questions