admin管理员组文章数量:1410682
Well I've just discovered JSON today but I have a problem using it correctly. I really can't find a solution...
Basically, I just want to count the elements of my array (count all the dM), and wrap on a specific element (dM1 for example).
Here is my code so that you can understand: /
Well I've just discovered JSON today but I have a problem using it correctly. I really can't find a solution...
Basically, I just want to count the elements of my array (count all the dM), and wrap on a specific element (dM1 for example).
Here is my code so that you can understand: http://jsfiddle/dRycS/9/
Share edited Mar 16, 2011 at 15:35 Jakub Hampl 40.6k10 gold badges79 silver badges111 bronze badges asked Mar 16, 2011 at 15:30 SindarSindar 10.9k7 gold badges34 silver badges45 bronze badges4 Answers
Reset to default 3Adding to what @Pointy said here is your code modified: JSFiddle Demo
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
var dMContent = {
"dM1" : [
{
"name" : "EeEeEeEe",
"link" : "http://test."
},
{
"name" : "FfFfFfFf",
"link" : "http://test."
},
{
"name" : "GgGgGgGg",
"link" : "http://test."
}
],
"dM2" : [
{
"name" : "EeEeEeEe",
"link" : "http://test."
},
{
"name" : "FfFfFfFf",
"link" : "http://test."
}
],
"dM3" : [
{
"name" : "EeEeEeEe",
"link" : "http://test."
}
]
};
var STORAGE = JSON.stringify(dMContent);
var parsed = JSON.parse(STORAGE);
// WHAT I WANT TO DO
// Count the number of dM
console.log(Object.size(parsed)); //gives you 3
//display the content
for(var i in parsed){
console.log('data in ' + i);
for(var j=0; j<parsed[i].length; j++){
console.log(parsed[i][j].name + ' ' + parsed[i][j].link);
}
}
What you've got there is not an Array; it's an Object. Array objects do have a "length" property, but Objects do not.
It's not clear exactly what you want; if you wanted to count every property of every object inside of "dMContent", you'd write something to count recursively. For a single "layer" of an object, something like this might be what you want:
function objectSize(obj) {
var count = 0;
for (var k in obj) {
if (obj.hasOwnProperty(k)) ++count;
}
return count;
}
In your code dMContent
is an Object, not an Array.
To count elements in an Object, do this:
var i = 0;
for (x in parsed) {
if (parsed.hasOwnProperty(x)) {
i++;
}
}
alert(i);
Try this: function objectCount(obj) {
objectcount = 0;
$.each(obj, function(index, item) {
objectcount = objectcount + item.length;
});
return objectcount;
}
objectCount(obj); where obj is a json object with json array as sub objects
本文标签: javascriptJSON count an Array elements and wrap inStack Overflow
版权声明:本文标题:javascript - JSON count an Array elements and wrap in - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744926155a2632609.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论