簡體   English   中英

如何使用字符串索引路徑獲取數組元素

[英]How to get element of array with string index path

我有一個數組,我有一個特定元素的路徑。

const str = "[0].subArray[2]"

const arr = [
  { subArray: [1, 2, 3, 4, 5] }, 
  { subArray: [32, 321, 11]}
];

是否可以以某種方式使用字符串路徑顯示元素?

您可以使用match實現結果。

在這里使用正則表達式

/[a-zA-Z]+|\d+/g

 const str = "[0].subArray[2]"; const arr = [{ subArray: [1, 2, 3, 4, 5] }, { subArray: [32, 321, 11] }]; function getValue(arr) { const [first, prop, index] = str.match(/[a-zA-Z]+|\\d+/g); return arr[first][prop][index]; } const result = getValue(arr); console.log(result);

您可以對一段路徑采用動態方法。

 function getValue(object, path) { return path .replace(/\\[/g, '.') .replace(/\\]/g, '') .split('.') .filter(Boolean) .reduce((o, k) => (o || {})[k], object); } console.log(getValue([{ subArray: [1, 2, 3, 4, 5] }, { subArray: [32, 321, 11] }], "[0].subArray[2]"));

您可以使用僅替換數字的正則表達式從字符串中提取鍵值,然后重建一個數組以輸出您所針對的子數組的部分,使用條件檢查索引以定位數組和子數組鍵/值。

 const arr = [ { subArray: [1, 2, 3, 4, 5] }, { subArray: [32, 321, 11]} ]; const str1 = "[0].subArray[2].subArray[1].subArray[4].subArray[1]" const str2 = "[1].subArray[2].subArray[0]" function removeNums(val){ return val.replace(/[^0-9]/g, '') } function getArrayValues(str){ // create an array by splitting the string at the dots const arrs = str.split('.') const results = [] for(let i in arrs){ // get the first index to locate the proper subarray // remove all but numbers from the indexes const firstIndex = removeNums(arrs[0]) // skip the first index and get remaining indexes // to get the rest of the subarrays values if(i > 0){ // remove all but numbers from the indexes const index = removeNums(arrs[i]) // construct an array of the proper values results.push(arr[firstIndex].subArray[index]) } } return results } console.log(getArrayValues(str1)) console.log(getArrayValues(str2))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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