簡體   English   中英

如何在 javascript 中修改單個 object 中的索引

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM