【问题标题】:Accessing the values of variables that are within an object property's string value? (JavaScript)访问对象属性字符串值中的变量值? (JavaScript)
【发布时间】:2020-07-24 19:43:06
【问题描述】:

使用 AWS S3 headObject 函数时,我收到一个 Javascript 对象,该对象具有一个名为 Restore 的属性,该属性设置如下:

{
     Restore: "ongoing-request=\"false\", expiry-date=\"Sun, 13 Aug 2017 00:00:00 GMT\""
}

或者像这样:

{
    Restore: "ongoing-request=\"true\""
}

我想访问和使用 Restore 属性的字符串值中的值,即正在进行的请求变量和到期日期变量,但问题是它们在字符串中。我怎样才能最好地解析恢复属性的字符串值,以便我可以获取正在进行的请求和到期日期的值并将它们设置为 Javascript 变量,以便我可以执行以下操作:

if(ongoingRequest === "true") {
    console.log("Bla bla bla");
}

或者:

let date = new Date(expiryDate);

【问题讨论】:

    标签: javascript string object amazon-s3


    【解决方案1】:

    您可以使用正则表达式和String.prototype.match 提取值。这是一个例子:

    const exampleOne = "ongoing-request=\"false\", expiry-date=\"Sun, 13 Aug 2017 00:00:00 GMT\"";
    const exampleTwo = "ongoing-request=\"true\"";
    
    console.log(parseRestore(exampleOne), parseRestore(exampleTwo));
    
    function parseRestore(str) {
      const ongoing = str.match(/ongoing-request=\"(true|false)\"/);
      const expiry = str.match(/expiry-date=\"(.+?)\"/);
      return {
        'ongoing-request': ongoing[1] === "true", 
        'expiry-date': (expiry || [])[1]
      };
    }

    【讨论】:

      【解决方案2】:

      此解决方案比 Andre Nuechter 的方法更通用。我不仅为持续请求和到期日期解析所有属性的字符串。
      首先,我将内部的双引号替换为单引号,因为它们更易于处理。比我将字符串与 string.match 全局拆分为来自属性及其值的字符串数组。我在每个字符串的末尾接受一个带有空格“,”的可选逗号,这是分隔条目所必需的。
      现在我将所有属性添加到结果对象中。为此,我在开头搜索一个字符串(prpertie-name),后跟等号并在引号中标记另一个字符串 (属性值)。最后,除了带有空格的可选逗号。从字符串匹配结果中,我可以获得属性的名称和值,因此我可以将其添加到结果中。

      function parseRestore(test) {
        test =  test.Restore.replace(/\"/gi,"\'");
        
        let entries = test.match(/[^=]+=\'[^\']+\'(, )?/g);
        let result = {};
      
        for (let i=0; i<entries.length; i++) {
          let entrySplit = entries[i].match(/^(.+)=\'(.+)\'(, )?$/);
        
          result[entrySplit[1]] = entrySplit[2];
        }
        
        return result;
      }
      
      let test_1 = {
           Restore: "ongoing-request=\"false\", expiry-date=\"Sun, 13 Aug 2017 00:00:00 GMT\""
      };
      let test_2 = {
          Restore: "ongoing-request=\"true\""
      }
      
      console.log( parseRestore( test_1 ) );
      console.log( parseRestore( test_2 ) );

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-14
        • 2018-01-24
        • 2013-12-02
        • 2019-10-15
        • 1970-01-01
        • 2012-11-28
        • 2019-10-18
        • 1970-01-01
        相关资源
        最近更新 更多