有很多關於如何根據數值對javascript數組進行排序的示例。然而,從myArray
獲取所有元素的適當方式是:prop1
,值爲value1
?Javascript:過濾二維數組
這裏是我的數組:
var myArray = [
{
"id":"2",
"name":"My name",
"properties":{"prop1":"value1"}
}];
感謝
有很多關於如何根據數值對javascript數組進行排序的示例。然而,從myArray
獲取所有元素的適當方式是:prop1
,值爲value1
?Javascript:過濾二維數組
這裏是我的數組:
var myArray = [
{
"id":"2",
"name":"My name",
"properties":{"prop1":"value1"}
}];
感謝
您可以只用點訪問或括號表示並將匹配成員推送到您的n EW /濾波陣列,例如:
var newArray = [];
for(var i=0, l = myArray.length; i<l; i++) {
if(myArray[i].properties.prop1 == "value1") newArray.push(myArray[i]);
}
你的問題是有點曖昧不過,如果你想獲得{"prop1":"value1"}
對象,而不是父母,那麼就改newArray.push(myArray[i])
到newArray.push(myArray[i].properties)
。
提供一個比較功能的任意屬性進行排序:
function compareMyObjects(a, b) {
var valA = a.properties.prop1.value1;
var valB = b.properties.prop1.value1;
if(valA > valB) return 1;
if(valA < valB) return -1;
return 0;
}
myArray.sort(compareMyObjects);
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort
這*排序*數組,而不是過濾它,也'prop1'是一個字符串,所以你已經走了一個屬性太:) – 2010-12-12 19:31:53
瀏覽數組中的每個元素。對於每個元素,檢查每個屬性以查看它是否與您正在查找的屬性相匹配。
function filterArray(array, property, value) {
var newArray = [];
for (var i = 0; i < array.length; i++) {
for (var j in array[i].properties) {
if (j === property && array[i].properties.hasOwnProperty(j)) {
if (array[i].properties[j] == value) {
newArray.push(array[i]);
}
}
}
}
}
這不檢查任何地方的值,它只是推動所有新的對象到一個新的數組,多次如果有超過1個孩子的財產。 – 2010-12-12 19:36:31
修正了它。發佈後我立即意識到自己的錯誤。 – mdarwi 2010-12-12 19:37:37
爲什麼直接訪問屬性時會循環? :) – 2010-12-12 19:40:45
var newarray=myarray.filter(function(itm){
return itm.properties.prop1==='value1';
});
過濾器,像陣列方法的indexOf和地圖,可能是值得提供的瀏覽器沒有它 - 這個版本是Mozilla開發者站點 -
if(!Array.prototype.filter){
Array.prototype.filter= function(fun, scope){
var L= this.length, A= [], i= 0, val;
if(typeof fun== 'function'){
while(i< L){
if(i in this){
val= this[i];
if(fun.call(scope, val, i, this)){
A[A.length]= val;
}
}
++i;
}
}
return A;
}
}
真的很乾淨的解決方案。非常感謝! – Industrial 2010-12-12 21:48:13
嗨尼克 - 請看看這裏; http://stackoverflow.com/questions/4433004/jquery-js-sorting-array-based-upon-another-array – Industrial 2010-12-13 20:08:04