2017-07-18 120 views
-1

我有我的數據集配置爲過濾多維數組

var x = [ 
     {"phaseName":"Initiation","phaseID":"595e382f1a1e9124d4e2600c"}, 
     {"phaseName":"Execution","phaseID":"595e38321a1e9124d4e2600d"} 
     ] 

我想寫一些功能,這給過濾數據的輸出。 例如

var y ="Initiation" 
samplefunction(y) 

和我得到的{"phaseName":"Initiation","phaseID":"595e382f1a1e9124d4e2600c"}

+0

你想測試對象的每個屬性? –

+0

'''phaseName''是關鍵字段嗎? – Champ

回答

0

你也可以使用一個簡單的循環for

var x = [{ 
 
    "phaseName": "Initiation", 
 
    "phaseID": "595e382f1a1e9124d4e2600c" 
 
    }, 
 
    { 
 
    "phaseName": "Execution", 
 
    "phaseID": "595e38321a1e9124d4e2600d" 
 
    } 
 
]; 
 

 
var y = "Initiation"; 
 

 
function samplefunction(value) { 
 
    var newArr = new Array(); //creating a new array to store the values 
 
    for (var i = 0; i < Object.keys(x).length; i++) { //looping through the original array 
 
    if (x[i].phaseName == value) {//check if the phase name coresponds with the argument 
 
     newArr.push(x[i]); //push the coressponding value to the new array 
 
    } 
 
    } 
 
    return newArr; //return the new array with filtered values 
 
} 
 
var result = samplefunction(y); 
 
console.log(result);

0

整條生產線使用Array#filter

var x = [{ 
 
    "phaseName": "Initiation", 
 
    "phaseID": "595e382f1a1e9124d4e2600c" 
 
    }, 
 
    { 
 
    "phaseName": "Execution", 
 
    "phaseID": "595e38321a1e9124d4e2600d" 
 
    } 
 
]; 
 

 
function filter(phaseName) { 
 
    return x.filter(item => { 
 
    return item.phaseName === phaseName; 
 
    }); 
 
} 
 

 

 
console.log(filter('Initiation'));

0

您可以測試爲需要的值的所有屬性和過濾陣列。

function filter(array, value) { 
 
    return array.filter(function (object) { 
 
     return Object.keys(object).some(function (key) { 
 
      return object[key] === value; 
 
     }); 
 
    }); 
 
} 
 

 
var data = [{ phaseName: "Initiation", phaseID: "595e382f1a1e9124d4e2600c" }, { phaseName: "Execution", phaseID: "595e38321a1e9124d4e2600d" }]; 
 

 
console.log(filter(data, "Initiation"));