![](/img/trans.png)
[英]How can I permanently modify a JSON object on a separate file with JavaScript?
[英]How can i modify indexing in a single object in javascript
我有一个 object 列表来存储这样的索引:
const initialIndexes = {
0: [0,1,2],
1: [0,1]
}
此时我有一个highlightedResultIndex
变量。 它给出了这样的索引:
highlightedResultIndex = 0 - case 1
highlightedResultIndex = 4 - case 2
highlightedResultIndex = 2 - case 3
...
最后我尝试通过highlightedResultIndex
得到以下结果
For the case 1:
result = {
0: 0, // index from initialIndexes
1: -1
}
For the case 2:
result = {
0: -1,
1: 1 // index from initialIndexes
}
For the case 3:
result = {
0: 2 // index from initialIndexes
1: -1
}
也许有一个简单的方法或者可能有某种算法,但我不知道如何研究它所以我想写在这里。 如果你能帮忙,我会很高兴。
编辑:
让我在这里举一些例子
// This is data from the server side.
const initialIndexes = {
0: [0,1,2,3],
1: [0,1,2],
2: [0,1,2],
3: [0,1,2,3,4]
}
// So, I need to index object like this by highlightedResultIndex variable
// highlightedResultIndex = 0
{
0:0,
1:-1,
2:-1,
3:-1
}
// highlightedResultIndex = 6
{
0: -1,
1:2,
2:-1,
3:-1
}
// highlightedResultIndex = 10
{
0: -1,
1:-1,
2:-1,
3:0
}
您可以采用所需的索引值并将其减少 arrays 的长度,直到它适合数组。
const initialIndexes = { 0: [0, 1, 2, 3], 1: [0, 1, 2], 2: [0, 1, 2], 3: [0, 1, 2, 3, 4] }, getIndices = n => Object.fromEntries(Object.entries(initialIndexes).map(([key, array]) => { const value = n >= 0 && n < array.length? array[n] // or just n: -1; n -= array.length; return [key, value]; }) ); console.log(getIndices(0)); // { 0: 0, 1: -1, 2: -1, 3: -1 } console.log(getIndices(6)); // { 0: -1, 1: 2, 2: -1, 3: -1 } console.log(getIndices(10)); // { 0: -1, 1: -1, 2: -1, 3: 0 }
.as-console-wrapper { max-height: 100%;important: top; 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.