我的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);
}
答案 0 :(得分:0)
答案 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
值。
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;
答案 3 :(得分:0)
您似乎正在使用AngularJS(DELETE /api/heroes/iron-man/team HTTP/1.1
Host: example.org
),因此您可以考虑使用原生角度过滤器或自定义过滤器来执行此操作。
$ctrl
示例代码段
for(var key in jsonData) {
if("expense" === jsonData[key]["type"]) {
console.log(jsonData[key]["label"]);
}
}
答案 4 :(得分:0)
尝试使用Id
方法根据Array.filter()
过滤数据。
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;