Not able to get object values - javascript

My array:
[
{
"date":"2018-04-01",
"time":[{"10:00":"12"},{"12:00":"25"}]
},
{
"date":"2018-04-02",
"time":[{"10:00":"12"},{"12:00":"25"}]
},
{
"date":"2018-04-03",
"time":[{"10:00":"12"},{"12:00":"25"}]
}
]
I need to get every date and time. To get this I am using a for loop. But not able to get date and time.
My script:
var slots = req.body.availableSlots;
var count = slots.length;
for(var i=0;i<count;i++){
console.log(slots[i]);
console.log(slots[i].date);
}
When getting date always says undefined.

It seems like req.body.availableSlots is coming as a multidimensional object array.
So full code need to be:-
var slots = req.body.availableSlots;
for(var i=0;i<count;i++){
var sub_array = slots[i];
for(j = 0; j<sub_array.length;j++){
console.log(sub_array[j].date);
}
}

Instead of using jquery library (jQuery.parseJSON()) use javascript inbuilt JSON.parse
var slots = '[{"date":"2018-04-01","time":[{"10:00":"12"},{"12:00":"25"}]},{"date":"2018-04-02","time":[{"10:00":"12"},{"12:00":"25"}]},{"date":"2018-04-03","time":[{"10:00":"12"},{"12:00":"25"}]}]';
slots = JSON.parse(slots);
var count = slots.length;
for(var i=0;i<count;i++){
console.log(slots[i].date);

Related

Parse Json array push javascript

I have Json Parse list which need to push each category list.
example :
listChartPeriods={"2018-05-04":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-11":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-18":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-25":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-06-01":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442]}
var categoryData = [];
var values = [];
for(var i=0;i<listChartPeriods.length;i++){
categoryData.push(listChartPeriods.slice(0,1)[0]); //here need to push each date
values.push(listChartPeriods[i])
}
expected out put:
categoryData=["2018-05-04","2018-05-11","2018-05-18","2018-05-25","2018-06-01"]
values=[21807210.5028442,21807210.5028442,21807210.5028442]//each category values
Just use Object.keys to get the dates in the array.
const listChartPeriods={"2018-05-04":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-11":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-18":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-25":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-06-01":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442]}
var categoryData = Object.keys(listChartPeriods);
console.log(categoryData);
Below should get the job done for you. A for in loop is your friend when it comes to working with objects.
var listChartPeriods={"2018-05-04":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-11":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-18":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-05-25":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442],"2018-06-01":[21807210.5028442,21807210.5028442,21807210.5028442,21807210.5028442]}
var categoryData = [];
for(var char in listChartPeriods){
for(var i = 0; i < listChartPeriods[char].length; i++){
categoryData.push(listChartPeriods[char][i]);
}
}
console.log(categoryData);
EDIT: Just read your updated question and you are only wanting the key names. You can also do this with a for in loop.
for(var char in listChartPeriods){
categoryData.push(char)
}
console.log(categoryData);
Following the solution:
for (let date in listChartPeriods){
categoryData.push(date);
let [first] = listChartPeriods[date];
values.push(first);
}
categoryData = ["2018-05-04", "2018-05-11", "2018-05-18", "2018-05-25", "2018-06-01"]
values = [21807210.5028442, 21807210.5028442, 21807210.5028442, 21807210.5028442, 21807210.5028442]

How to print localStorage array in html for loop?

I have an array in my localStorage which contains ["January","Febuary"]
I want it to be displayed in HTML preferably like this:
Month
January
Febuary
So I've tried this code:
function show(){
for(let i = 0;i < localStorage.length;i++){
var date = JSON.parse(localStorage.getItem("date"));
}
for(var b = 0; b < nameLength; b++){
document.getElementById('storageOut').innerHTML = date[b];
console.log(date[b]);
}
}
My code above does work however, the line "document.getElementById('storageOut').innerHTML = date[b];"only prints out the last data in the array, but when i check the console it prints out both.
You create the variable date in the first for-loop and assign it to one value each iteration. Easiest way would probably be to do it in a single for-loop instead:
function show(){
for(let i = 0;i < localStorage.length;i++){
var date = JSON.parse(localStorage.getItem("date"));
document.getElementById('storageOut').innerHTML = date;
}
}
Although, if you want all the dates, you should probably append it to the innerHtml:
...innerHTML += date;
Or rather:
...innerText += date;
Assuming your contents are stored in local storage key named data. Try the following.
const data = JSON.parse(localStorage.getItem('data'))
data.forEach(item => {
document.getElementById('storageOut').innerHTML += item
})

Read through JSON number array using javascript loop [duplicate]

This question already has answers here:
Loop through an array in JavaScript
(46 answers)
Closed 5 years ago.
I`m trying to write a loop that will read through a nested number array.
The JSON file that I`m reading goes like this. each number key represents event dates.
json reference for startdate and end date
enter image description here
I have below javascript code that reads per var i = 1 or j = 1.
I`d like to read through entire nested number from dates and store them somewhere.
$(document).ready(function () {
$.getJSON('http://app.toronto.ca/cc_sr_v1_app/data/edc_eventcal_APR?limit=500', function (data) {
var data = data;
var i = 2;
var obj = data[i].calEvent;
var bingname = obj.eventName;
var j = 1;
var startdate = obj.dates[j].startDateTime;
var time = new Date(startdate);
var starttime = time.getFullYear()+'-' + (time.getMonth()+1) + '-'+time.getDate();
var name = JSON.stringify(bingname);
document.getElementById("bingname").innerHTML = name;
document.getElementById("bingtime").innerHTML = starttime;
var name = firebase.database().ref("/bing").set({
EventName : name,
EventStart : starttime
});
});
});
Now, I should use something of incremental loop for var j. But I'm not sure how.
The problem for me is that json retrieved in obj.dates[j] doesn't seem like an array. I can't seem to read it as list of numbers to read through. Help is much appreciated.
If anyone can even sort this nearest to furthest from today's date that'd be Einstein:)
You will get an array of objects, that includes a callEvent object that has a dates property which is an array with objects with the property's startDateTime and endDateTime.
It will look like following:
[
{
callEvent: {
dates: [
{startDateTime: '', endDateTime: ''},
// more objects with start- and endDateTime
]
}
},
// more callEvent objects..
]
Now your code should loop through the array to get all callEvent objects and loop through all dates objects inside each callEvent.
$(document).ready(function () {
$.getJSON('http://app.toronto.ca/cc_sr_v1_app/data/edc_eventcal_APR?limit=500', function (array) {
// loop through all elements in the array
for (var i = 0; i < array.length; i++) {
// loop through all dates inside the array
for (var j = 0; j < array[i].calEvent.dates.length; j++) {
console.log(array[i].callEvent.dates[j].startDateTime)
console.log(array[i].callEvent.dates[j].endDateTime)
}
}
});
});
Assuming the dates are valid JSON (JSON Validator), then you should just be able to get the data and loop through it:
for (var i=0;i<data.length;++i) {
console.log(data[i].startDateTime);
console.log(data[i].endDateTime);
}

How to "clean" an array in javascript?

I am stuck here. How can I clean this array:
{"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]}
So that it looks like:
["5201521d42","52049e2591","52951699w4"]
I am using Javascript.
You just need to iterate over the existing data array and pull out each id value and put it into a new "clean" array like this:
var raw = {"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var clean = [];
for (var i = 0, len = raw.data.length; i < len; i++) {
clean.push(raw.data[i].id);
}
Overwriting the same object
var o = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
for (var i = o.data.length; i--; ){
o.data[i] = o.data[i].id;
}
What you're doing is replacing the existing object with the value of its id property.
If you can use ES5 and performance is not critical, i would recommend this:
Edit:
Looking at this jsperf testcase, map vs manual for is about 7-10 times slower, which actually isn't that much considering that this is already in the area of millions of operations per second. So under the paradigma of avoiding prematurely optimizations, this is a lot cleaner and the way forward.
var dump = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var ids = dump.data.map(function (v) { return v.id; });
Otherwise:
var data = dump.data;
var ids = [];
for (var i = 0; i < data.length; i++) {
ids.push(data[i].id);
}
Do something like:
var cleanedArray = [];
for(var i=0; i<data.length; i++) {
cleanedArray.push(data[i].id);
}
data = cleanedArray;
Take a look at this fiddle. I think this is what you're looking for
oldObj={"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
oldObj = oldObj.data;
myArray = [];
for (var key in oldObj) {
var obj = oldObj[key];
for (var prop in obj) {
myArray.push(obj[prop]);
}
}
console.log(myArray)
Use Array.prototype.map there is fallback code defined in this documentation page that will define the function if your user's browser is missing it.
var data = {"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var clean_array = [];
for( var i in data.data )
{
for( var j in data.data[i] )
{
clean_array.push( data.data[i][j] )
}
}
console.log( clean_array );
You are actually reducing dimension. or you may say you are extracting a single dimension from the qube. you may even say selecting a column from an array of objects. But the term clean doesn't match with your problem.
var list = [];
var raw = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
for(var i=0; i < raw.data.length ; ++i){
list.push(raw.data[i].id);
}
Use the map function on your Array:
data.map(function(item) { return item.id; });
This will return:
["5201521d42", "52049e2591", "52951699w4"]
What is map? It's a method that creates a new array using the results of the provided function. Read all about it: map - MDN Docs
The simplest way to clean any ARRAY in javascript
its using a loop for over the data or manually, like this:
let data = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},
{"id":"52951699w4"}]};
let n = [data.data[0].id,data.data[1].id, data.data[2].id];
console.log(n)
output:
(3) ["5201521d42", "52049e2591", "52951699w4"]
Easy and a clean way to do this.
oldArr = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]}
oldArr = oldArr["data"].map(element => element.id)
Output: ['5201521d42', '52049e2591', '52951699w4']

How to separate the values from two dimension array in js?

jQuery.get("ChkNewRspLive.php?lastmsgID=" + n, function(newitems){
//some code to separate values of 2d array.
$('#div1').append(msgid);
$('#div2').append(rspid);
});
Let's say the value of newitems is [["320","23"],["310","26"]]
I want to assign "320" and "310" to var msgid.
I want to assign "23" and "26" to var rspid.
How to do that?
I tried to display newitems and the output is "Array". I tried to display newitems[0] and the output is blank.
If I redeclare var newitems = [["320","23"],["310","26"]]; it works. So I guess the variable newitems from jQuery.get is something wrong. Is it I cannot pass the array from other page to current page through jQuery directly?
Regarding the array on other page, if echo json_encode($Arraytest); the output is [["320","23"],["310","26"]] but if echo $Arraytest; the output is Array. How do I pass the array from other page to currently page by jQuery.get?
I don't totally understand the question but I'm going to assume you want the values in an array, as two values can't be stored in one (scalar) variable simultaneously.
jQuery.get("ChkNewRspLive.php?lastmsgID=" + n, function(newitems){
//some code to separate values of 2d array.
var msgid = [],
rspid = [];
for( i = 0 ; i < newitems.length ; i++){
msgid[msgid.length] = newitems[i][0];
rspid[rspid.length] = newitems[i][1];
}
//msgid now contains ["320","310"]
//rspid now contains ["23","26"]
});
Bear in mind those are in the function scope. If you want to use them outside of that scope instantiate them outside. see: closure
You can use pluck from underscore.js: http://documentcloud.github.com/underscore/#pluck
var msgid = _(newitems).pluck(0)
var rspid = _(newitems).pluck(1)
Try this:
function getArrayDimension(arr, dim) {
var res = [];
for(var i = 0; i < arr.length; i++) {
res.push(arr[i][dim]);
}
return res;
}
var newitems = [["320","23"],["310","26"]];
var msgid = getArrayDimension(newitems, 0);
var rspid = getArrayDimension(newitems, 1);
msgid and rspid are arrays holding the 'nth' dimention.
Tnx

Categories