我将数据设置为本地存储中名为“todo”的键。
结构是这样的。
key: todo
value : [{"text":"text1","idx":1},
{"text":"text2","idx":2},
{"text":"text4","idx":4}]
如何找到idx = "4"的对象的索引?
例如,idx = 1 的对象的索引为 0。
key: todo
value : [{"text":"text1","idx":1} => index: 0
{"text":"text2","idx":2} => index: 1
{"text":"text4","idx":4}] => index: 2
最佳答案
假设您已经从本地存储中解析了 JSON 字符串(如果没有,您可以使用 JSON.parse()
),您可以使用 .findIndex()
获取具有给定 id 的对象的索引:
const arr = [{
"text": "text1",
"idx": 1
}, {
"text": "text2",
"idx": 2
}, {
"text": "text4",
"idx": 4
}];
const search = 4;
const res = arr.findIndex(({idx}) => idx === search); // find index of object where idx is equal to search (4)
console.log(res); // 2
关于javascript - (javascript) 本地存储值索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59442206/