【问题标题】:Returning only true boolean value JSON objects仅返回真正的布尔值 JSON 对象
【发布时间】:2020-06-13 02:36:54
【问题描述】:

我想在 javascript/typescript 中返回 JSON 对象,这些对象具有“团队”的真正布尔值。我使用的 JSON 示例是:

{
    "state": "Texas",
    "stateId": 1,
    "team": true
},
{
    "state": "California",
    "stateId": 5,
    "team": false
},
{
    "state": "Rhode Island",
    "stateId": 14,
    "team": true
}

所以它应该以数组的形式返回 Texas 和 Rhode Island。到目前为止,我已经编写了以下代码,但它没有考虑不同的布尔值,我不确定为什么:

jsonString: any;
stateArray: any;

constructor() {
this.jsonString = JSON.stringify(data);
this.stateArray = JSON.parse(this.jsonString);

  this.stateArray.filter(function(array) {
  if (data["team"] === true) {
      return array;
  }
});

console.log(this.stateArray);

非常感谢您的帮助。

【问题讨论】:

    标签: javascript arrays json typescript boolean


    【解决方案1】:

    Array.filter 的回调会针对数组的每个元素执行,并且需要一个以单个元素作为参数并返回 boolean 值的回调。试试:

    let stateArray = [{
        "state": "Texas",
        "stateId": 1,
        "team": true
    },
    {
        "state": "California",
        "stateId": 5,
        "team": false
    },
    {
        "state": "Rhode Island",
        "stateId": 14,
        "team": true
    }]
    
    let result = stateArray.filter(function(state) {
      return state.team;
    });
    
    console.log(result);

    【讨论】:

    • 您好 mickl 感谢您的帮助,我尝试了您的解决方案,但它提供了相同的输入。我编辑了我的原始帖子,以表明在我的函数中我已经解析了 JSON 并预先对其进行了字符串化。如果你知道这个的解决方案?
    • filter 返回一个新数组,因此您必须在某处分配该值(它不会修改现有值),尝试:this.stateArray = this.stateArray .filter(...)
    • 我明白了,代码现在可以工作了!谢谢你的澄清
    【解决方案2】:

    使用 ES6 的箭头操作符,你甚至可以在一行中完成。

    请找到下面的代码。

    let stateArray = [{
        "state": "Texas",
        "stateId": 1,
        "team": true
    },
    {
        "state": "California",
        "stateId": 5,
        "team": false
    },
    {
        "state": "Rhode Island",
        "stateId": 14,
        "team": true
    }]
    
    let result = stateArray.filter(state => state.team);
    
    console.log(result);

    【讨论】:

      猜你喜欢
      • 2019-04-29
      • 2020-05-22
      • 1970-01-01
      • 1970-01-01
      • 2020-01-21
      • 2021-07-18
      • 2019-07-01
      • 1970-01-01
      • 2019-10-09
      相关资源
      最近更新 更多