简体   繁体   English

将 JSON object 字符串转换为带有字符串键的数组

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

I have an JSON string with an object: {"foo1":"bar1","foo2":"bar2"}我有一个 JSON 字符串和一个 object: {"foo1":"bar1","foo2":"bar2"}

How can I convert this into an array with string keys?如何将其转换为带有字符串键的数组? The result should be the same as this:结果应该与此相同:

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

I need a very fast way, since I have to convert often arrays with more than 100,000 items.我需要一个非常快速的方法,因为我必须经常转换超过 100,000 个项目的 arrays。

To literally create your "array with extra properties" , you can use Object.assign()要从字面上创建“具有额外属性的数组” ,您可以使用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