过滤多维数组

时间:2017-07-18 08:38:24

标签: javascript arrays sorting

我的数据集配置为

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

我想编写一些函数来提供过滤数据的输出。 例如

var y ="Initiation" 
samplefunction(y) 

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

的整行

3 个答案:

答案 0 :(得分:1)

使用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'));




答案 1 :(得分: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"));




答案 2 :(得分: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);
&#13;
&#13;
&#13;