Home > Software engineering >  Converting an JSON object string into an array with string keys
Converting an JSON object string into an array with string keys

Time:08-10

I have an JSON string with an 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.

CodePudding user response:

To literally create your "array with extra properties", you can use 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);

  • Related