[英]Iterating over JSON object
I'm having some troubles iterating in a json object.我在 json 对象中迭代时遇到了一些麻烦。 I'm currently saving the table properties of a some web page in a cookie.
我目前正在将某个网页的表属性保存在 cookie 中。 The value of the cookie is an array of objects which I serialize.
cookie 的值是我序列化的对象数组。 The typical value of an array with 2 entries is something like:
具有 2 个条目的数组的典型值类似于:
cookieValue=["{ "PageID": "1391", "PageSize": "100"}", "{ "PageID": "2341", "PageSize": "50"}"]
My problem is iterating in this array now.我的问题是现在在这个数组中迭代。 I want to be able to check if there is any duplicate entry to update its PageSize (if applicable) or to read it in order to set the page size when a user goes back to the same page.
我希望能够检查是否有任何重复条目来更新其 PageSize(如果适用)或读取它以便在用户返回同一页面时设置页面大小。
I've tried this so far:到目前为止我已经尝试过这个:
for (var key in cookieValue) {
if(cookieValue.hasOwnProperty(key) ){
console.log(key + " -> " + cookieValue[key]);
}
}
which give me an output like:这给了我一个输出,如:
0 -> { "PageID": "1391_tabela", "PageSize": "100"}
1 -> { "PageID": "1391_tabela", "PageSize": "50"}
2 -> { "PageID": "1391_tabela", "PageSize": "10"}
My question is how am i able to access the value of PageID in each entry.我的问题是我如何能够访问每个条目中 PageID 的值。
Thanks in advance提前致谢
I am not sure if I understand you correctly but I think you should just use我不确定我是否正确理解你,但我认为你应该使用
cookieValue[key]["PageID"]
together:一起:
for (var key in cookieValue) {
if(cookieValue.hasOwnProperty(key) ){
console.log(key + " -> " + cookieValue[key] + " -> " + cookieValue[key]["PageID"]);
}
}
If you only want to access the value of PageId in each entry, you can view example here :如果您只想访问每个条目中 PageId 的值,您可以在此处查看示例:
var cookieValue=[{ "PageID": "1391", "PageSize": "100"}, { "PageID": "2341", "PageSize": "50"}];
for (key in cookieValue) {
alert(cookieValue[key]["PageID"]);
}
Manipulate the data using a javascript array for easier code.使用 javascript 数组操作数据以简化代码。
One way that should work for you:一种应该适合您的方法:
var mycookieArray = JSON.parse(cookieValue); var mycookieArray = JSON.parse(cookieValue);
Iterate through it with:遍历它:
for(String s : myCookieArray) { console.log(s.PageID); for(String s : myCookieArray) { console.log(s.PageID); }
}
It seems that you need to get the object by the PageId.看来您需要通过 PageId 获取对象。 Here is a function
这是一个函数
function getPageById(pageId) {
for (var pageObj in cookieValue) {
if (pageObj.PageId === pageId)
return pageObj;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.