简体   繁体   中英

Associative Arrays - Javascript

I am trying to populate an associative array, in a dynamic way. I have been reading a lot of documents but unable to figure out the right way.

The outcome of the code will be

op{
    '0': value1, value2
    '128': value3, value4, value 6
    '630': value7
}

This is what i have written and is not working

var arr =  [];
for(var i = 1; i <=last ; i++){
    var key = rec[i].op;
    var op = {};
    op[key] = rec[i].description;
    arr.push(op);
}

The most recent record is overwriting the previous record.

I think you want something like:

var op = {};
for(var i = 0; i < last ; i++)
{
    var key = rec[i].op;
    if (op[key] == undefined) 
    {
        op[key] = [];
    }
    op[key].push(rec[i].description);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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