2017-01-25 164 views
1

我有屬性的JS對象命名Attr可能包含屬性的不同排列,如Color[]Manufacturer[]Brands[]檢查JS對象包含數組

我如何檢查Attr包含給定屬性陣列? 例如,我如何檢查Attr是否包含Color[]

我試過,但它不工作:

if (Attr.hasOwnProperty('Color')) { 
    console.log("Has Colors array") 
} 

enter image description here

+0

[如何創建一個最小,完整和可驗證的示例](https://stackoverflow.com/help/mcve)。 – Andreas

+0

顯示如何定義Attr。 – charlietfl

+0

屬性是我從服務器 – user829174

回答

1

由於attrs本身是對象的數組,你在你的解決方案接近,但是你需要往下走一個多水平。

要檢查是否在attrs第一目標(即attr[0]你可以明顯地循環並使用類似attr[i]也。)已經給定的數組,你使用這種方法是最好的:

if (attrs[0].hasOwnProperty("Color")) { 
    . . . do something . . . 
} 

。 。 。或者,甚至:

if (attrs[0].Color !== undefined) { 
    . . . do something . . . 
} 

要麼將​​工作,既可以更好地適合於不同的情況(例如,第一可能會更好,如果你正在傳遞的數組作爲變量的名字,如果你是第二個檢查特定的數組名稱)。


更新:

爲了記錄在案,依據是什麼在你的屏幕截圖所示,你的結構attr變量是:

attr = [ 
    { 
     AspectRatio: [...], 
     Binding: [...], 
     Brand: [...], 
     Color: [...], 
     EAN: [...], 
     EANList: [...] 
    } 
] 

這應該更好地展現你爲什麼在你做檢查之前再降一級。

+1

未定義它不是一個字符串。您必須使用'attrs [0] .Color!= undefined'。 –

+0

我想這是爲......亞歷山德魯問題是什麼? – user829174

+1

@ user829174,請看看這裏:https://jsfiddle.net/h5av96a2/1/ –

0

你必須檢查是否Color數組存在,它是一個array。假設Attr=attrs[0](根據您的更新)。

if (Attr.Color!=undefined && Array.isArray(Attr)) { 
    console.log("Has Colors array"); 
} 
+0

OP添加的代碼,所以現在它是不正確的。 – epascarello

0

您可以使用Array.isArray功能的檢查,如果Color是一個數組。此外,作爲一個高爾夫的條件,你可以檢查,如果顏色屬性存在與否。從更新後的帖子看來,您可以忽略該檢查。

if (attrs[0].Color && Array.isArray(attrs[0].Color)) { 

    console.log("Has Colors array") 
} 
相關問題