0

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.

2

2 Answers 2

1

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().

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.