【问题标题】:Searching array key with reserved keyword使用保留关键字搜索数组键
【发布时间】:2022-01-21 21:39:25
【问题描述】:

我已经创建了如下数组

["lists", { "getByTitle": "CardOperation" }, "items", { "filter": "Id eq 1" }, { "select": ["Title", "CustomerAge"] }];

现在一个键作为 filter 我想找到它以知道它存在于数组中,但由于它是保留关键字,我无法搜索它

我累了

array.filter //not working

array["filter"] // not working

在这种情况下我应该怎么做,我试图找出数组是否有一个对象在任何索引处都有一个带有过滤键的对象

【问题讨论】:

    标签: javascript arrays multidimensional-array


    【解决方案1】:

    这可能就是你想要的:

    循环遍历数组,如果存在带有“filter”键的对象,则返回true,否则返回false。

    const myArray = ["lists", { "getByTitle": "CardOperation" }, "items", { "filter": "Id eq 1" }, { "select": ["Title", "CustomerAge"] }]
    
    const hasObject = myArray.find(obj => typeof obj === 'object' && obj !== null && obj["filter"]) ? true : false;
    
    console.log(hasObject);
    
    const objectIndex = myArray.findIndex(obj => typeof obj === 'object' && obj !== null && obj["filter"]);
    
    if(objectIndex == -1) {
        // there is no match in the array
    }

    【讨论】:

    • 感谢您不分位置的回复,能否找到钥匙
    • 这不起作用,因为有时过滤器键不是他们的
    • 您是否试图找出数组是否在任何索引处都有一个带有 filter 键的对象?
    • 没错,试图找出数组中是否有一个对象,其键为 filter 在任何索引处
    • 刚刚更新了我的答案,看看吧。
    【解决方案2】:

    当然,您可以对单词过滤器进行过滤,除非您的结果具有过滤器方法,否则它不会被保留

    const list = ["lists", { "getByTitle": "CardOperation" }, "items", { "filter": "Id eq 1" }, { "select": ["Title", "CustomerAge"] }];
    
    const obj = list
      .filter(item => typeof item === "object" && 
                      Object.keys(item).includes("filter")); // loking for the key name "filter"
    
    console.log(obj[0].filter); // using the key named filter

    【讨论】:

      【解决方案3】:

      访问数组中项目的最简单方法是使用它们的索引。


      const array = ["arrays", { "getByTitle": "CardOperation" }, "items", { "filter": "Id eq 1" }, { "select": ["Title", "CustomerAge"] }];
      
      console.log(array[3].filter);
      
      /* Output: Id eq 1 */

      希望你的问题得到解决

      【讨论】:

      • 我正在尝试找出数组是否在任何索引处都有一个带有 filter 键的对象
      【解决方案4】:

      你必须搜索数组[3].filter

      【讨论】:

      • 这不起作用,因为有时过滤器键不是他们的
      • 这是常量数组的场景,否则你必须创建一个包含动态对象的数组
      猜你喜欢
      • 2018-04-17
      • 1970-01-01
      • 2012-06-04
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-16
      相关资源
      最近更新 更多