我已经搜索了网络和stackoverflow来回答这个问题。
如何从动态密钥中检索值,该动态密钥也嵌套在localstorage中。 我尝试了很多例子,似乎无处可去。 我需要一个循环来执行任务,但是哪种类型。
我如何获得' uniqid'具有来自localstorage的嵌套动态密钥SCI-4的值,其中包含:
simpleCart_items:{"SCI-4":{"quantity":4,"id":"SCI-4","price":8,"name":"12 fried chicken","flavours":"cola","code":"1001","cartid":"561","uniqid":"592dcd08b5fcc"}}
这允许我查看localstorage。
var obj = localStorage;
Object.keys(obj).forEach(function(key){
var value = obj[key];
console.log(key + ':' + value);
});
如何迭代获取任何值?
这个问题的不同之处在于我试图从具有动态值的嵌套键中获取值。如果不知道密钥怎么拉值?循环应该是什么样的?
答案 0 :(得分:0)
认为这是您正在寻找的,:))
Object.keys(obj).forEach(function (key) {
Object.keys(obj[key]).forEach(function (val) {
//console.log(val);
if(val === "uniqid")
{
//logic here
console.log(obj[key][val]);
}
});
});
答案 1 :(得分:0)
如果您只是将结构存储为单个键的单个值,则以后很容易将其提取出来。
// How do I get the 'uniqid' value which has the nested dynamic key SCI-4 from localstorage which reads:
// This is our simulated result from pulling from localStorage
var lsString = `{
"simpleCart_items": {
"SCI-4": {
"quantity":4,
"id":"SCI-4",
"price":8,
"name":"12 fried chicken",
"flavours":"cola",
"code":"1001",
"cartid":"561",
"uniqid":"592dcd08b5fcc"
}
}
}`;
// First, remember that localStorage stores strings, so we must parse the string
// back into an object:
var lsObj = JSON.parse(lsString);
var keyName = Object.keys(lsObj.simpleCart_items).toString();
// Now, we can go directly to the property we want:
console.log(lsObj.simpleCart_items[keyName].uniqid);

答案 2 :(得分:0)
localStorage需要正确访问,如下所示。 问题主要通过以下方式解决:
var obj = JSON.parse(localStorage.simpleCart_items);
Object.keys(obj).forEach(function (key) {
Object.keys(obj[key]).forEach(function (val) {
//console.log(val);
if (val === "quantity")
{
//logic here
console.log(obj[key][val]);
}
});
});