簡體   English   中英

將 JSON object 字符串轉換為帶有字符串鍵的數組

[英]Converting an JSON object string into an array with string keys

我有一個 JSON 字符串和一個 object: {"foo1":"bar1","foo2":"bar2"}

如何將其轉換為帶有字符串鍵的數組? 結果應該與此相同:

var myArray = [];
myArray["foo1"] = "bar1";
myArray["foo2"] = "bar2";

我需要一個非常快速的方法,因為我必須經常轉換超過 100,000 個項目的 arrays。

要從字面上創建“具有額外屬性的數組” ,您可以使用Object.assign()

 const json = `{"foo1":"bar1","foo2":"bar2"}`; // assign the parsed object properties on to an array const myArray = Object.assign([], JSON.parse(json)); console.log("myArray:", myArray); // still an empty array // but the properties do actually exist console.log("myArray.foo1:", myArray.foo1); console.log("myArray.foo2:", myArray.foo2);

暫無
暫無

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

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