-1

在 Javascript 中,我试图:

从 lib-One-5dc422e9 中删除 5dc422e9 的 ID,

从 lib-Six-5dc422e9gfg 中删除 5dc422e9gfg 的 ID 等等。

我想保留 JSON 字符串中的所有内容,只想删除末尾的 ID 部分lib-*-

{
   "data":{
      "Library":{
         "Checkout":{
            "invoiceId":"12dfdf454546",
            "checkoutDetail":{
               "invoiceTransactionId":"5ab422e9",
               "invoicePaymentDetail":{
                  "bookId":"lib-One-5dc422e9",
                  "checkoutPeriods":[
                     {
                        "startDate":"2017-04-14T19:00:00.000",
                        "endDate":"2017-05-19T19:00:00.000"
                     }
                  ],
                  "invoice":{
                     "bookId":"lib-Six-5dc422e9gfg",
                     "checkObject":true
                  }
               }
            }
         }
      }
   }
}
4

2 回答 2

1

String#replace与一些正则表达式一起使用。

replace() 方法返回一个新字符串,其中模式的部分或全部匹配被替换替换。模式可以是字符串或正则表达式,替换可以是字符串或每次匹配调用的函数。如果 pattern 是字符串,则仅替换第一个匹配项。

replace方法的第二个参数我用了一个回调函数

正则表达式

IE:/(lib-[^-]+-)[^"]+/g

解释

[^-]+ 找到任何不存在的东西-

(lib-[^-]+-)匹配任何东西lib-*-

[^"]+找到任何不是"(id)的东西

解决方案

const data = {"data":{"Library":{"Checkout":{"invoiceId":"12dfdf454546","checkoutDetail":{"invoiceTransactionId":"5ab422e9","invoicePaymentDetail":{"bookId":"lib-One-5dc422e9","checkoutPeriods":[{"startDate":"2017-04-14T19:00:00.000","endDate":"2017-05-19T19:00:00.000"}],"invoice":{"bookId":"lib-Six-5dc422e9gfg","checkObject":true}}}}}}};

const res = JSON.stringify(data).replace(/(lib-[^-]+-)[^"]+/g, (_, match)=>match);

console.log(JSON.parse(res, null, 2));

于 2019-11-07T19:13:18.790 回答
0

如果 ID 的格式总是像这样“lib-[word]-”,你可以这样做:

"lib-Six-5dc422e9gfg".split("-")[2]
于 2019-11-07T19:23:49.113 回答