[英]Javascript: How to Iterate Object [Key: value] but skip some keys ([fastest way possible])
如果給出類似以下的腳本:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test DOC</title>
<script type="text/javascript" src="../nt_scr/jq_1.9.js"></script>
<script type="text/javascript">
var mainObj = { 0: { "fruitName":"Lemon",
"fruitColor":"green",
"fruitTaste":"bad"},
1: { "fruitName":"Mango",
"fruitColor":"Yellow",
"fruitTaste":"Yammy"},
2: {
"fruitName":"Banana",
"fruitColor":"Yellow",
"fruitTaste":"Yammy"},
"skip_these":
{
"team1":"Liverpool",
"team2":"Manchester United"
}
}
var collect_data = $.parseJSON(JSON.stringify(mainObj)),
getFruitNames=[],getFruitColors=[], getFruitTastes=[];
$.each( collect_data,function(index,val){
//console.log(val); //Un-comment this console.log to see the contents of 'val'
//----->Here is the Challenge:,---------\\\
if(/*How do you SKIP if val is something like */ "val.team1" || "val.team2"){
getFruitNames.push(val.fruitName);
getFruitColors.push(val.fruitColor);
getFruitTastes.push(val.fruitTaste);
//This works well so long as we have not yet reached the "skip_these":
//Once there, it reports an error because there is no "skip_these".fruitName or "skip_these".fruitColor
}
console.log( getFruitNames[index])// Run a test out put :: NOTICE the "Undefined" in the Console. How to avoid that?
//To see well, Comment the previous console.log <<the one on top>>
})
</script>
</head>
<body>
</body>
</html>
我有時以前做過,但是不知何故,我的大腦現在一片空白...。 (請使用您的jQuery
運行)
(不是jquery-香草)迭代屬性並跳過特定鍵:(未測試語法,但應該可以)
var skipped = ['keySkipped'];
for (var someProperty in someObject) {
if (someObject.hasOwnProperty(someProperty) && skipped.indexOf(someObject[someProperty] === -1)) {
// do stuff
}
}
說明:迭代屬性,並且屬性是否確實包含在對象中,但不包含在skiped
執行任何操作
正如JQuery文檔所述 ,
返回非false與for循環中的continue語句相同; 它將立即跳至下一個迭代。
因此,按照您的示例,可以使用以下內容跳過具有不需要的屬性的對象:
的JavaScript
$.each( collect_data,function(index,val){
//console.log(val); //Un-comment this console.log to see the contents of 'val'
//----->Here is the Challenge:,---------\\\
if(val.team1 || val.team2){
return true;
}
getFruitNames.push(val.fruitName);
getFruitColors.push(val.fruitColor);
getFruitTastes.push(val.fruitTaste);
//This works well so long as we have not yet reached the "skip_these":
//Once there, it reports an error because there is no "skip_these".fruitName or "skip_these".fruitColor
console.log( getFruitNames[index])//No "Undefined"
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.