var times = [{ "Start": "2016-01-26\r\n", "End": "2016-01-26\r\n" }, { "Start": "2016-01-21\r\n", "End": "2016-01-29\r\n" }]
I am trying to run a loop in jQuery to get the start and end date but I am unable to fetch the value in a variable. I am very new to JSON so any help will be appreciated.
You can use Array.forEach
to loop over data and .push
to insert into new array.
Also I have added code to remove \r\n
. Refer following post for reference.
var data = [{ "Start": "2016-01-26\r\n", "End": "2016-01-26\r\n" }, { "Start": "2016-01-21\r\n", "End": "2016-01-29\r\n" }]; var startDate = []; var endDate = []; var trimRegex = /\r?\n|\r/g; data.forEach(function(obj) { startDate.push(obj.Start.replace(trimRegex,'')); endDate.push(obj.End.replace(trimRegex,'')); }); console.log(startDate, endDate);
var obj = [{ "Start": "2016-01-26\r\n", "End": "2016-01-26\r\n" }, { "Start": "2016-01-21\r\n", "End": "2016-01-29\r\n" }]; for (var counter = 0; counter < obj.length; counter++) { console.log("Start date: " + obj[counter].Start); console.log("End date: " + obj[counter].End); }
So for getting the value of JSON first we see which data structure we are using for json ie it is only single object or a array.
if it a array like yours data is an array in that case we can fetch data like
var k=[{"Start":"2016-01-26\r\n","End":"2016-01-26\r\n"},{"Start":"2016-01-21\r\n","End":"2016-01-29\r\n"}];
for(i=0;i<k.length;i++)
{console.log(k[i].Start)}
Will run a loop till array length and try to fetch key. if its only a object then we can do directly like
var k={"Start":"2016-01-26\r\n","End":"2016-01-26\r\n"}
console.log(k.Start)
I hope it will help
you can use jquery each
var times = [{ "Start": "2016-01-26\r\n", "End": "2016-01-26\r\n" }, { "Start": "2016-01-21\r\n", "End": "2016-01-29\r\n" }]; $.each(times, function(index, obj) { console.log("Start date: " + obj.Start); console.log("End date: " + obj.End); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
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.