2010-08-20 75 views
1

如何使用數組查詢對象?使用數組查詢對象(不包含第三方腳本)

var myArray = ['A','C'] 

使用myArray的,我怎麼能得到與[「1」,「3」]返回的數組了以下(以前JSON對象)的(不使用第三方查詢腳本 - 除非它是jQuery的: )

[ { "property1": "1", 
    "property2": "A" 
    }, 
    { "property1": "2", 
    "property2": "B" 
    }, 
    { "property1": "3", 
    "property2": "C" 
    } ] 

回答

4

你可以嵌套循環:

var myArray = ['A','C']; 
var json = [{ 
    'property1': '1', 
    'property2': 'A' 
}, { 
    'property1': '2', 
    'property2': 'B' 
}, { 
    'property1': '3', 
    'property2': 'C' 
}]; 

var result = new Array(); 
for (var i = 0; i < myArray.length; i++) { 
    for (var j = 0; j < json.length; j++) { 
     if (json[j].property2 === myArray[i]) { 
      result.push(json[j].property1); 
     } 
    } 
} 

// at this point result will contain ['1', '3'] 
+0

Darin !!甜蜜的解答!謝謝我的'1'和'3':D – Kyle 2010-08-20 11:40:42

2

您可以步行數組是這樣的:

var json = [ { "property1": "1", 
    "property2": "A" 
    }, 
    { "property1": "2", 
    "property2": "B" 
    }, 
    { "property1": "3", 
    "property2": "C" 
    } ]; 

var myArray = ['A', 'C']; // Here is your request 
var resultArray = []; // Here is the container for your result 

// Walking the data with an old-fashioned for loop 
// You can use some library forEach solution here. 
for (var i = 0, len = json.length; i < len; i++) { 
    var item = json[i]; // Caching the array element 

    // Warning! Not all browsers implement indexOf, you may need to use a library 
    // or find a way around 
    if (myArray.indexOf(item.property2) !== -1) { 
     resultArray.push(item.property1); 
    } 
} 

console.log(resultArray); 
+0

+1感謝伊戈爾爲此解決方案!似乎是一個很好的替代解決方案。 – Kyle 2010-08-20 11:41:49

+0

這真的不是替代方法:)除了'indexOf'部分外,它是一樣的。我真的很驚訝與Emile的回答有多接近,因爲在回答這個問題之前我沒有看到他的解決方案。 – 2010-08-20 11:47:40