簡體   English   中英

javascript,添加數組“周圍”對象

[英]javascript, add array “around” object

我一直在尋找答案,但是似乎找不到答案,對於已經存在的答案,我深表歉意。

我希望有一個對象,讓我們這樣說:

{
    name: 'myname',
    items: [
        {
            itemID: '1'
        },
        {
            itemID: '2'
        },
        {
            itemID: '3'
        }
    ]
}

問題是,每當“項目”中只有一個對象時,它看起來像這樣:

{
    name: 'myname',
    items: {
        itemID: '1'
    }
}

這意味着我的forEach函數將中斷,因為“項”不再是對象數組。 forEach中每個“項目”對象內部都有大量數據和工作,因此我寧願不必同時使用forEach和另一個函數,而是將其轉換為數組並僅使用forEach。

這就是我想做的:

if (items is not array) {
    //Convert the object to this:
    {
        name: 'myname',
        items: [
            {
                itemID: '1'
            }
        ]
    }
}

我在確定項目是對象數組還是對象對象時遇到問題(在兩種情況下,typeof項都將返回“對象”),如果不是數組,則如何將其轉換為數組。 非常感謝您的幫助或提示

您可以根據需要用數組包裝項目,例如:

(Array.isArray(obj.items) ? obj.items : [obj.items]).
   forEach(function(item){

     .
     .
     .

   });

使用Array.isArray(obj)檢查var是否為array

例如:

 var object1 = { name: 'myname', items: [{ itemID: '1' }, { itemID: '2' }, { itemID: '3' }] }; var object2 = { name: 'myname', items: { itemID: '1' } }; if (Array.isArray(object1.items)) { document.write('Hey guy I\\'m an array!<br />'); } else { document.write('Hey guy I\\'m not an array!<br />'); } if (Array.isArray(object2.items)) { document.write('Hey guy I\\'m an array!<br />'); } else { document.write('Hey guy I\\'m not an array!<br />'); } 

除了其他答案外,我僅提供此答案,因為我認為它們不夠清楚。

var items = obj.items;
if( ! Array.isArray(items) ){
   items = [items];
}

items.forEach(function(){
   // iterate over each item
});

這些步驟可以組合在一起,如CD ..的答案所示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM