【问题标题】:Filtering array with specific values过滤具有特定值的数组
【发布时间】:2016-04-26 04:03:14
【问题描述】:

我有这个 JSON:

{
  "1": {
    "PerId":"10900662",
    "Name":"Cueball",
    "Email":"cueb@example.com",
    "DepartId":"11"
  },
  "2": {
    "PerId":"10900664",
    "Name":"Megan",
    "MuEmail":"megan@example.com",
    "DepartId":"11"
  },
  "3": {
    "PerId":"10900665",
    "Name":"Beret Guy",
    "MuEmail":"bg@example.com",
    "DepartId":"12"
  }
}

我想用特定的DepartId 过滤

这是我测试过的代码,来自this Stack Overflow question

<html>
<body>
  Test!
</body>
<script>
  var y = JSON.parse('{"1":{"PerId":"10900662","Name":"Cueball","Email":"cueb@example.com","DepartId":"11"},"2": {"PerId":"10900664","Name":"Megan","MuEmail":"megan@example.com","DepartId":"11"},"3": {"PerId":"10900665","Name":"Beret Guy","MuEmail":"bg@example.com","DepartId":"12"}}');
  var z = y.filter(function (i,n){return n.DepartId == '11'})
</script>
</html>

在这种情况下,y 返回一个对象,但 Firefox 抛出 y.filter is not a function. 的错误

我希望 y 以类似的形式返回

{
  "1": {
    "PerId":"10900662",
    "Name":"Cueball",
    "Email":"cueb@example.com",
    "DepartId":"11"
  },
  "2": {
    "PerId":"10900664",
    "Name":"Megan",
    "MuEmail":"megan@example.com",
    "DepartId":"11"
  }
}

以 JavaScript 对象的形式。如何让它发挥作用?

【问题讨论】:

  • filter() 可以申请数组而不是对象
  • 你得到的是一个对象。过滤器只适用于数组,它应该是[ { "PerId":"10900662", "Name":"Cueball", "Email":"cueb@example.com", "DepartId":"11" }, { "PerId":"10900664", "Name":"Megan", "MuEmail":"megan@example.com", "DepartId":"11" } ];

标签: javascript jquery json


【解决方案1】:

filter()Array 原型上定义。它不能用于对象。

您可以使用Object.keys() 获取对象中的所有键,并使用for 循环遍历它们。

// Get all keys from the `obj`
var keys = Object.keys(obj),
    result = {};


// Iterate over all properties in obj
for (var i = 0, len = keys.length; i < len; i++) {
    // If the ID is to be filtered
    if (obj[keys[i]].DepartId === '11') {

        // Add the object in the result object
        result[keys[i]] = obj[keys[i]];
    }
}

var obj = {
    "1": {
        "PerId": "10900662",
        "Name": "Cueball",
        "Email": "cueb@example.com",
        "DepartId": "11"
    },
    "2": {
        "PerId": "10900664",
        "Name": "Megan",
        "MuEmail": "megan@example.com",
        "DepartId": "11"
    },
    "3": {
        "PerId": "10900665",
        "Name": "Beret Guy",
        "MuEmail": "bg@example.com",
        "DepartId": "12"
    }
};

var keys = Object.keys(obj),
    result = {};

for (var i = 0, len = keys.length; i < len; i++) {
    if (obj[keys[i]].DepartId === '11') {
        result[keys[i]] = obj[keys[i]];
    }
}

console.log(result);
document.body.innerHTML = '<pre>' + JSON.stringify(result, 0, 4);

我建议更改数据格式以使用对象数组。那么filter()就可以直接应用于数组了。

var arr = [{
    "PerId": "10900662",
    "Name": "Cueball",
    "Email": "cueb@example.com",
    "DepartId": "11"
}, {
    "PerId": "10900664",
    "Name": "Megan",
    "MuEmail": "megan@example.com",
    "DepartId": "11"
}, {
    "PerId": "10900665",
    "Name": "Beret Guy",
    "MuEmail": "bg@example.com",
    "DepartId": "12"
}];

var result = arr.filter(obj => obj.DepartId === '11');
console.log(result);

var arr = [{
    "PerId": "10900662",
    "Name": "Cueball",
    "Email": "cueb@example.com",
    "DepartId": "11"
}, {
    "PerId": "10900664",
    "Name": "Megan",
    "MuEmail": "megan@example.com",
    "DepartId": "11"
}, {
    "PerId": "10900665",
    "Name": "Beret Guy",
    "MuEmail": "bg@example.com",
    "DepartId": "12"
}];

var result = arr.filter(obj => obj.DepartId === '11');

console.log(result);
document.body.innerHTML = '<pre>' + JSON.stringify(result, 0, 4);

【讨论】:

    【解决方案2】:

    您正在尝试对对象使用数组过滤器。再看一遍这个例子。

    $([ // this is an array of objects
        {"name":"Lenovo Thinkpad 41A4298","website":"google222"},
        {"name":"Lenovo Thinkpad 41A2222","website":"google"}
      ])
        .filter(function (i,n){
            return n.website==='google';
        });
    

    【讨论】:

      【解决方案3】:

      filter是数组函数的原型,不是object,所以这里不能用。

      为了实现输出,我们可以在object上使用for-in循环

      var y = JSON.parse('{"1":{"PerId":"10900662","Name":"Cueball","Email":"cueb@example.com","DepartId":"11"},"2": {"PerId":"10900664","Name":"Megan","MuEmail":"megan@example.com","DepartId":"11"},"3": {"PerId":"10900665","Name":"Beret Guy","MuEmail":"bg@example.com","DepartId":"12"}}');
      
      var res = {}
      for(var key in y){
        if(y[key].DepartId === '11')
         res[key] = y[key]
      }
      console.log(res)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-25
        • 1970-01-01
        • 1970-01-01
        • 2022-01-07
        相关资源
        最近更新 更多