使用jquery在列表对象中获取相同值的计数。使用Ajax调用方法我在客户端获取列表对象,但我不知道如何在每个行对象中获取相同值的计数。
因为PO_NM在其他对象中是相同的,我希望计数如
化学品-2 电气 - 2 水-1
[{“ID”:13,“PO_ID”:1,“PO_NM”:“化学”,“POINT_NAME”:“TES HFJGH KH”},{“ID”:13,“PO_ID”:1,“ PO_NM“:”化学品“,”POINT_NAME“:”KRUTIKA PATEL“},{”ID“:14,”PO_ID“:2,”PO_NM“:”电气“,”POINT_NAME“:”SDA SHFKJ KJSJDHF KJSHDKJ JK“} ,{“ID”:14,“PO_ID”:2,“PO_NM”:“电气”,“POINT_NAME”:“KJHG S DJKFH JSKJSDKJFH KJ”},{“ID”:15,“PO_ID”:3,“PO_NM” “:”水“,”POINT_NAME“:”ERTERSHFKJ HNSJFH KJS“}]”
答案 0 :(得分:0)
编辑:
抱歉,之前发布了错误的回复。看看使用库来实现这一点_countBy
var els = [];
els.push({"ID":13,"PO_ID":1,"PO_NM":"Chemical","POINT_NAME":"TES HFJGH KH"});
els.push({"ID":13,"PO_ID":1,"PO_NM":"Chemical","POINT_NAME":"KRUTIKA PATEL"});
els.push({"ID":14,"PO_ID":2,"PO_NM":"Electrical","POINT_NAME":"SDA SHFKJ KJSJDHF KJSHDKJ JK"});
els.push({"ID":14,"PO_ID":2,"PO_NM":"Electrical","POINT_NAME":"KJHG S DJKFH JSKJSDKJFH KJ"});
els.push({"ID":15,"PO_ID":3,"PO_NM":"Water","POINT_NAME":"ERTERSHFKJ HNSJFH KJS"});
var cnts = _.countBy(els,'PO_NM');
alert(JSON.stringify(cnts));
console.log(cnts);
https://jsfiddle.net/HappyiPhone/370mL2v2/4/
以前的答案:
查看.filter
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
var els = [];
els.push({ID: '13', 'POINT_NAME': 'TEST', PO_ID: '1', 'PO_NM': 'Chemical'});
els.push({ID: '14', 'POINT_NAME': 'TEST', PO_ID: '2', 'PO_NM': 'Electrical'});
els.push({ID: '15', 'POINT_NAME': 'TEST', PO_ID: '3', 'PO_NM': 'Chemical'});
els.push({ID: '16', 'POINT_NAME': 'TEST', PO_ID: '4', 'PO_NM': 'Electrical'});
var els2 = els.filter(function(word){
return word.PO_NM == 'Chemical';
})
console.log(els2);
$(els2).each(function(i){
alert(els2[i].PO_NM + ' ' + els2[i].ID);
})
答案 1 :(得分:0)
如果你想要一个没有下划线的答案,你可以使用它:
var myArr = [
{ID: '1', 'prop1': 'val1', prop2: 'a', prop3: 'value1'},
{ID: '2', 'prop1': 'val1', prop2: 'b', prop3: 'value3'},
{ID: '3', 'prop1': 'val2', prop2: 'b', prop3: 'value1'}
];
function countObjects(arr, prop) {
var results = {};
for(var i = 0; i < arr.length; i++) {
var name = arr[i][prop];
if(results.hasOwnProperty(name)) {
results[name] = results[name] + 1;
} else {
results[name] = 1;
}
}
return results;
}
console.log(countObjects(myArr, "prop1"));
console.log(countObjects(myArr, "prop2"));
console.log(countObjects(myArr, "prop3"));
&#13;