简体   繁体   中英

So I am trying to get a set of items from an array using a for loop and displaying them into a context menu sub menu, but somehow I am not able to

So I am trying to get a list of clients from an array and then display them one by one into a context menu sub menu. But somehow I am confused on how to do it. Any help would be really appreciated.

So below is the code that I have already tried but I am always getting the last item from the list like this, while I would like to get all the items from the list one under the other.

action: function () {
    var itemDisp = [];  
    var client;
    var arrayLength = clients_array.length;
    for (var i = 0; i < arrayLength; i++) {
        client = clients_array[i].toString().split(',');
        displayClient.push(client[0] + ' - ' + client[1]);
        clientDisp = client[0] + ' - ' + client[1];
        itemDisp = { label: displayClient[i]};   
    }
} 
return { 
    "AddClient" : {
        label: "Add Client",                        
        "submenu": { 
            itemDisp
        }
    }
}

Right now I am getting the last item from the array with the above code, while I would like to get all the items found in the array.

It looks like you need an array. However in your code you are overwriting the array with an object. This might explain why you only see the last object.

Instead try this:

function () {
    var itemDisp = [];  
    var client;
    var arrayLength = clients_array.length;
    for (var i = 0; i < arrayLength; i++) {
        client = clients_array[i].toString().split(',');
        displayClient.push(client[0] + ' - ' + client[1]);
        clientDisp = client[0] + ' - ' + client[1];

        // Important part here!
        itemDisp.push({ label: displayClient[i]});
    }
} 
return { 
    "AddClient" : {
        label: "Add Client",   
        // Also changed. We just pass the array.                     
        "submenu": itemDisp
    }
}

By using the array push method we add the object to the end of the itemDisp array.

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