我的JSON如下:
{
"sales": [{
"manager": "alberic",
"surgeon": "Dr Barry Biggins",
"amount": "300",
"country": "USA",
"percent-seller": "30",
"antiquity": "June 2017",
"date": "6"
}, {
"manager": "support",
"surgeon": "Dr Barry Biggins",
"amount": "300",
"country": "UK",
"percent-seller": "20",
"antiquity": "June 2017",
"date": "2"
}, {
...
}]
}
我想从sales
manager = "support"
和date = "2"
中检索{{1}}对象。我如何在jQuery中解决这个问题?
谢谢!
答案 0 :(得分:2)
只需你可以使用filter()
方法并使用你的条件,如果条件变为true,则返回元素,否则忽略元素。
data= {"sales": [{
"manager": "alberic",
"surgeon": "Dr Barry Biggins",
"amount": "300",
"country": "USA",
"percent-seller": "30",
"antiquity": "June 2017",
"date": "6"
}, {
"manager": "support",
"surgeon": "Dr Barry Biggins",
"amount": "300",
"country": "UK",
"percent-seller": "20",
"antiquity": "June 2017",
"date": "2"
},
]
};
var matchedElements = data.sales.filter(function(element) {
return (element.manager == 'support' && element.date == '2');
});
console.log(matchedElements);
//if you want to access surgeon of first element of matchedElements
console.log(matchedElements[0].surgeon);
//if you want to access surgeon of all elements in matchedElements
for(i in matchedElements)
{
console.log(matchedElements[i].surgeon);
}
答案 1 :(得分:1)
您filter
sales
数组。
如果您想支持旧浏览器,请务必添加上述链接中的polyfill。
var matchingSales = jsonData.sales.filter(function(sale) {
return sale.manager == 'support' && sale.date == '2';
});
答案 2 :(得分:1)
var data = {
"sales": [{
"manager": "alberic",
"surgeon": "Dr Barry Biggins",
"amount": "300",
"country": "USA",
"percent-seller": "30",
"antiquity": "June 2017",
"date": "6"
}, {
"manager": "support",
"surgeon": "Dr Barry Biggins",
"amount": "300",
"country": "UK",
"percent-seller": "20",
"antiquity": "June 2017",
"date": "2"
}]
};
$.each(data.sales, function(i, v) {
if (v.manager == 'support' && v.date == '2') {
console.log(v.manager)
console.log(v.surgeon)
console.log(v.amount)
}
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
使用.each()