简体   繁体   中英

Convert Multidimensional String to Array Javascript

I do have variable contains the complete string, which I need to be treated like Array. Like:

var events='[{"title":"Appointment","start":"10:30:00"},{"title":"Appointment","start":"11:00:00"},{"title":"Appointment","start":"11:15:00"},{"title":"Appointment","start":"11:45:00"}]';

Now, I need to treat and work that string like an array to pass that multidimensional Array to a function.

Thanks.

You can use JSON.parse() to convert the String into an object with objects = JSON.parse(events); after that, access is possible to access it with objects[0].title

See further details about json.parse here: https://www.w3schools.com/js/js_json_parse.asp

Your code should look like

var events='[{"title":"Appointment","start":"10:30:00"}, {"title":"Appointment","start":"11:00:00"},{"title":"Appointment","start":"11:15:00"},{"title":"Appointment","start":"11:45:00"}]';
var objects = JSON.parse(events);
console.log(objects[0].title);

Another (but bad way) is using eval() . parsing the string with eval will execute the code and returns a result (In this case a javascript object) that can be accessed the same way. However, if you have malicous code in in the string, it will be executed as well. (See https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/eval )

If you can, use JSON.parse().

Try with JSON.parse() :

 var events = '[{"title":"Appointment","start":"10:30:00"},{"title":"Appointment","start":"11:00:00"},{"title":"Appointment","start":"11:15:00"},{"title":"Appointment","start":"11:45:00"}]'; var eventsArr = JSON.parse(events); function myFunction(arr){ arr.forEach(function(i){ // loop here to get information console.log('Title:',i.title + ' and start time:', i.start); }); } myFunction(eventsArr); // pass the array here 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM