【问题标题】:How to get element of array with string index path如何获取具有字符串索引路径的数组元素
【发布时间】:2021-07-05 18:17:11
【问题描述】:

我有一个数组,我有一个特定元素的路径。

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

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

是否有可能以某种方式使用字符串路径显示元素?

【问题讨论】:

  • 出于安全考虑不推荐,但可以使用:eval("arr"+str)
  • 还有一个东西叫JSONPath
  • 你是如何得到那个字符串的?这似乎是项目早期其他问题的结果。
  • 大量 split() 和正则表达式可能会有所帮助:P
  • 字符串是否总是采用这种精确的格式,还是可以变化?

标签: javascript arrays string parsing


【解决方案1】:

您可以对路径的长度采取动态方法。

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]"));

【讨论】:

  • 但是我该如何替换这个元素呢?我们从 getValue 函数中找到的元素。
  • 您可以存储键数组并弹出最后一个键,以便与最新对象一起用作属性访问器。
【解决方案2】:

您可以使用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);

【讨论】:

    【解决方案3】:

    您可以使用仅针对数字的正则表达式替换从字符串中提取键值,然后重建一个数组以输出您所针对的子数组的部分,使用条件检查索引以定位数组和子-数组键/值。

    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))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多