簡體   English   中英

如何從具有字符串拆分的字符串數組創建 object?

[英]How to create an object from an array of strings with string splits?

我有一個字符串數組。 我需要創建一個 object,其中的鍵是 = 符號左側的字符串中的值,它們的值是字符串中 = 符號右側的字符串中的文本。 你能告訴我如何實現這個嗎?

    const testArray = ["test1=25", "test2=1", "test3=2015-01-02" ]
    
    
     const testObjects = ??? 

     // i want to get similar object
      {
        test1: "25",
        test2: "1",
        test3 : "2015-01-02",
      }

您可以使用Object.fromEntries()方法和.map來准備條目:

 const testArray = ["test1=25", "test2=1", "test3=2015-01-02" ] const entries = testArray.map(e => e.split('=')); const result = Object.fromEntries(entries); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top: 0 }

我確信有更優化的方法可以做到這一點,但是這確實可以為您帶來您想要的結果。 請注意這里沒有驗證,這意味着如果您的數組中的某個項目缺少等號“=”(或您要使用的任何分隔符),它將失敗。

 const testArray = ["test1=25", "test2=1", "test3=2015-01-02" ]; let testObj = {}; testArray.forEach(item => { testObj[item.split("=")[0]] = item.split("=")[1]; }); console.log(testObj);

 const testArray = ["test1=25", "test2=1", "test3=2015-01-02" ] let t = testArray.map((e)=>e.split('=')); const obj = {}; for (const key of t) { obj[key[0]] = key[1]; } console.log ( 'obj: ',obj);

暫無
暫無

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

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