我有下面的字典,我希望得到所有通知的长度(4)。
[
{
"name": "3 Bedroom Fixer Upper",
"city": "Santa Rosa",
"id": 1,
"state": "CA",
"date_added": "2/3/14",
"completion_status": "20",
"notifications": [
"Quarterly Checklist",
"Pre-Summer",
"Annual Checklist"
],
"sq_ft": 2200,
"year_built": 1994,
"bedrooms": 3,
"bathrooms": 2.5,
"lot_size": 2.5
},
{
"name": "Ski Cabin",
"city": "Tahoe",
"id": 2,
"state": "CA",
"date_added": "3/3/14",
"completion_status": "45",
"notifications": [
"Quarterly Checklist"
],
"sq_ft": 1950,
"year_built": 1984,
"bedrooms": 3.5,
"bathrooms": 2,
"lot_size": 3
}
];
我能够获得单个对象通知的长度(例如all_properties [0] .notifications.length = 3),但all_properties.notifications.length不返回任何内容。返回所有通知的长度的语法是什么? (4)
http://jsfiddle.net/dakra/U3pVM/
很抱歉,如果我使用了关于JSON词典的错误术语(我是他们的新手。)
答案 0 :(得分:1)
您可以使用Array.prototype.reduce:
进行一些函数式编程function findSum(arr) {
return arr.reduce(function (a, b) {
return a + b.notifications.length;
}, 0);
}
并将其称为findSum(all_properties)
。
对于名为arrays
的数组中的多个数组:
var totalSum = 0;
for (var i = 0; i < arrays.length; i += 1) {
totalSum = findSum(arrays[i]);
}
答案 1 :(得分:0)
您可以使用Array's reduce功能
var data = [...your data array...]
var num = data.reduce(function(a,b){
return a+b.notifications.length;
},0);
console.log("Number of notifications:",num);