如何为json数据添加过滤器

时间:2017-05-21 09:19:55

标签: javascript json

我的json数据中有很多这样的条目。 "类型"由两个属性组成,即收入和支出。如何打印"标签"其中type ="费用"在使用JavaScript。 下面的这个json数据只是一个例子。 Check the image to get a better idea of json data.

  "expenses_veterinary":{
      label:"Veterinary, breeding, and medicine"
      name:"expenses_veterinary"
      total:0
      type:"expense"
  }
console.log($ctrl.gold_standard_categories); prints all the json data.

我尝试了下面编写的代码,但它无效。

  if($ctrl.gold_standard_categories.name.type=expense){
       console.log($ctrl.gold_standard_categories.label);
  } 

5 个答案:

答案 0 :(得分:0)

由于if语句中的单个等号,它会打印所有数据。

这意味着您始终尝试将值“expense”分配给type属性,因此if语句将始终评估为true。

您打算做的是compare值,而不是赋值。

答案 1 :(得分:0)

https://jsfiddle.net/yxL4rpj2/

假设在var money中存储了json响应

var grouppedMoney = {
    expenses: [],
    incomes: []
 };

for(var i = 0; i <= money.length - 1; i++){

    for(moneyType in money[i]){
    var _typeString = money[i][moneyType].type == 'expense' ? 'expenses' : 'incomes';

    grouppedMoney[_typeString].push(money[i][moneyType]);

  }

}

答案 2 :(得分:0)

以下是基本示例。对您的对象进行迭代,看type值等于expense,然后打印label值。

&#13;
&#13;
var data = {
"expenses_veterinary":{
      "label":"Veterinary, breeding, and medicine",
      "name":"expenses_veterinary",
      "total":0,
      "type":"income"
  },
  
  "expenses_car":{
      "label":"bus and truck",
      "name":"expenses_car",
      "total":0,
      "type":"expense"
  }
};
 
for (var property in data) {
    if (data.hasOwnProperty(property)) {
        // do stuff
	if(data[property]['type']=='expense'){
	    console.log(data[property]['label']);
	}
    }
}
&#13;
&#13;
&#13;

答案 3 :(得分:0)

您似乎正在使用AngularJS(DELETE /api/heroes/iron-man/team HTTP/1.1 Host: example.org ),因此您可以考虑使用原生角度过滤器或自定义过滤器来执行此操作。

BTW,使用vanilla JS,这个简单的循环将起作用:

$ctrl

示例代码段

for(var key in jsonData) {
  if("expense" === jsonData[key]["type"]) {
    console.log(jsonData[key]["label"]);
  }
}

答案 4 :(得分:0)

尝试使用Id方法根据Array.filter()过滤数据。

Working Fiddle

&#13;
&#13;
type="expense"
&#13;
var obj = {
  "expenses_goods":{
      "label":"expenses_goods",
      "name":"expenses goods",
      "total":0,
      "type":"income"
  },
  "expenses_cars":{
      "label":"expenses_cars",
      "name":"expenses cars",
      "total":0,
      "type":"expense"
  },
  "expenses_veterinary":{
      "label":"expenses_veterinary",
      "name":"expenses veterinary",
      "total":0,
      "type":"income"
  }
};

var res = Object.keys(obj).filter(item => { return obj[item].type == 'expense' });

for (var i in res) {
  document.getElementById("result").innerHTML = obj[res[i]].label;
}
&#13;
&#13;
&#13;