Disable JSON auto merging data with same ID - javascript

I have a simple ajax call to PHP Select request like this :
$.ajax({
type: "POST",
url: "/renforts/_getIntervenantManager",
data: {
IDMission : IDMission,
IDManager : IDManager
},
dataType : 'json',
global: false,
success: function(respond)
{
console.log(respond);
}
});
and my PHP file look like :
$CUIDManager = $_POST['IDManager'];
$IDMission = $_POST['IDMission'];
$pdo_sql_renforts = DB_renforts();
$sql= "SELECT [IDIntervenant], [week], [hours], [year] FROM ....";
$requete = $pdo_sql_renforts->prepare($sql);
$requete->execute(array($IDMission, $IDMission,$CUIDManager));
$tab = $requete->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($tab);
So far so good here, because I get my respond.
My problem now is that my sql select return something like :
IDIntervenant
week
hours
year
1
22
16
2021
1
23
16
2021
1
24
16
2021
2
22
16
2021
3
25
16
2021
But the JSON respond that I have is merging the line with same ID and create stranges arrays in the first appearance of an ID like this :
0 : {
"CUIDIntervenant": "1",
"week": [
[
"22",
"23"
],
"24"
],
"hours": [
[
"16",
"16"
],
"16"
],
"year": [
[
"2021",
"2021"
],
"2021"
],
}
1 : {
"CUIDIntervenant": "1",
"week": "23",
"hours": "16",
"year": "2021"
}
2 : {
"CUIDIntervenant": "1",
"week": "24",
"hours": "16",
"year": "2021"
}
3 : {
"CUIDIntervenant": "2",
"week": "22",
"hours": "16",
"year": "2021"
}
4 : {
"CUIDIntervenant": "3",
"week": "25",
"hours": "16",
"year": "2021"
}
And what I want is :
0 : {
"CUIDIntervenant": "1",
"week": "22",
"hours": "16",
"year": "2021"
}
1 : {
"CUIDIntervenant": "1",
"week": "23",
"hours": "16",
"year": "2021"
}
2 : {
"CUIDIntervenant": "1",
"week": "24",
"hours": "16",
"year": "2021"
}
3 : {
"CUIDIntervenant": "2",
"week": "22",
"hours": "16",
"year": "2021"
}
4 : {
"CUIDIntervenant": "3",
"week": "25",
"hours": "16",
"year": "2021"
}

The json is correct, something is happening inside jquery that messing it up. Try receive it as text and convert it manually:
$.ajax({
type: "POST",
url: "/renforts/_getIntervenantManager",
data: {
mission: IDMission,
IDManager: IDManager
},
dataType: 'text',
global: false,
success: function(respond) {
console.log("original response");
console.log(respond);
console.log("JSON");
console.log(JSON.parse(respond));
}
});

Related

Sorting multiple array elements alphabetically

I was wondering if there was a better or smarter way of sorting objects in JavaScript when sorting for multiple items?
For example, if I have the following JSON:
json = [
{ "type": "car", "year": 2007, "origin": "AUS" },
{ "type": "truck", "year": 2021, "origin": "USA" },
{ "type": "car", "year": 2004, "origin": "CA" },
{ "type": "bike", "year": 2016, "origin": "UK" },
{ "type": "truck", "year": 2020, "origin": "CA" },
{ "type": "bike", "year": 2000, "origin": "AUS" }
]
If I wanted to sort it by type then year how would I do that in the same .sort function?
I've currently got it doing one, then the other - but when I try to combine them it doesn't seem to output correctly:
// one after other
json.sort( ( a, b ) => {
a = a.type.toLowerCase();
b = b.type.toLowerCase();
return a < b ? -1 : a > b ? 1 : 0;
})
.sort( ( a, b ) => {
a = a.year;
b = b.year;
return a < b ? -1 : a > b ? 1 : 0;
});
Returning:
[
{ "type": "bike", "year": 2000, "origin": "AUS" },
{ "type": "car", "year": 2004, "origin": "CA" },
{ "type": "car", "year": 2007, "origin": "AUS" },
{ "type": "bike", "year": 2016, "origin": "UK" },
{ "type": "truck", "year": 2020, "origin": "USA" },
{ "type": "truck", "year": 2021, "origin": "CA" }
]
When it should return (all the types together, then by year):
[
{ "type": "bike", "year": 2000, "origin": "AUS" },
{ "type": "bike", "year": 2016, "origin": "UK" },
{ "type": "car", "year": 2004, "origin": "CA" },
{ "type": "car", "year": 2007, "origin": "AUS" },
{ "type": "truck", "year": 2020, "origin": "USA" },
{ "type": "truck", "year": 2021, "origin": "CA" }
]
In the sort callback, compare the items' type property. If one is lexographically greater/smaller, sort it before/after the other item accordingly.
Otherwise, you can return the result after subtracting the two items' year property:
const arr = [
{ "type": "car", "year": 2007, "origin": "AUS" },
{ "type": "truck", "year": 2021, "origin": "USA" },
{ "type": "car", "year": 2004, "origin": "CA" },
{ "type": "bike", "year": 2016, "origin": "UK" },
{ "type": "truck", "year": 2020, "origin": "CA" },
{ "type": "bike", "year": 2000, "origin": "AUS" }
]
const sorted = arr.sort((a,b) => a.type.localeCompare(b.type) || a.year - b.year)
console.log(sorted)
Credit to DraganS
If you don't want the comparison to be case-sensitive, you can set localeCompare's sensitivity option to accent:
const arr = [
{ "type": "car", "year": 2007, "origin": "AUS" },
{ "type": "truck", "year": 2021, "origin": "USA" },
{ "type": "car", "year": 2004, "origin": "CA" },
{ "type": "bike", "year": 2016, "origin": "UK" },
{ "type": "truck", "year": 2020, "origin": "CA" },
{ "type": "bike", "year": 2000, "origin": "AUS" }
]
const sorted = arr.sort((a,b) => a.type.localeCompare(b.type, undefined, {sensitivity:'accent'}) || a.year - b.year)
console.log(sorted)
If you do one sort followed by a different sort, the final sort overrides any previous sort.
Combine them into the same lambda
json.sort( ( a, b ) => {
aType = a.type.toLowerCase();
bType = b.type.toLowerCase();
aYear = a.year;
bYear = b.year;
return aType < bType
? -1
: aType > bType
? 1
: aYear < bYear
? -1
: aYear > bYear
? 1
: 0;
})
Though this has gotten pretty unreadable. You can have multiple comparison functions:
let compareByType = (a, b) => {
aType = a.type.toLowerCase();
bType = b.type.toLowerCase();
return (aType<bType) ? -1 : (aType>bType ? 1 : 0);
}
let compareByYear = (a,b) => {
return a.year - b.year;
}
json.sort(
(a, b) => {
let s = compareByType(a, b);
if(s !== 0) {
return s;
} else {
return compareByYear(a, b);
}
}
);
You can do this with one sort by first checking if the types are equal. If so, sort on the date. If not, sort on the type.
const json = [
{ "type": "car", "year": 2007, "origin": "AUS" },
{ "type": "truck", "year": 2021, "origin": "USA" },
{ "type": "car", "year": 2004, "origin": "CA" },
{ "type": "bike", "year": 2016, "origin": "UK" },
{ "type": "truck", "year": 2020, "origin": "CA" },
{ "type": "bike", "year": 2000, "origin": "AUS" }
]
// one after other
json.sort( ( a, b ) => {
a = a.type.toLowerCase();
b = b.type.toLowerCase();
if (a === b) {
return a.year - b.year;
}
return a < b ? -1 : 1;
});
console.log(json);

Group values with the same key in an array of objects

To display data in highcharts.js I need to turn the following data:
"personas": [
{
"category":"Persona1",
"month":"6",
"week":"24",
"day":"18",
"dayaverage":0.5,
"weekaverage":1.33333333333333,
"monthaverage":1.53571428571429
},
{
"category":"Persona2",
"month":"6",
"week":"24",
"day":"18",
"dayaverage":0.146477031224456,
"weekaverage":0.194758246723904,
"monthaverage":0.601273296708939
},
{
"category":"Persona3",
"month":"6",
"week":"24",
"day":"18",
"dayaverage":1.25559947299078,
"weekaverage":1.43618513323983,
"monthaverage":0.998426393184655
},
{
"category":"Persona4",
"month":"6",
"week":"24",
"day":"18",
"dayaverage":0.799332962757087,
"weekaverage":0.923262727610554,
"monthaverage":0.769477297163179
},
{
"category":"Persona5",
"month":"6",
"week":"24",
"day":"18",
"dayaverage":0.669041769041769,
"weekaverage":0.67394482002558,
"monthaverage":0.670944920469891
},
{
"category":"Persona6",
"month":"6",
"week":"24",
"day":"18",
"dayaverage":0.656381486676017,
"weekaverage":0.722973507315144,
"monthaverage":0.69689774371321
},
{
"category":"Persona7",
"month":"6",
"week":"24",
"day":"18",
"dayaverage":0.540495407737267,
"weekaverage":0.576413277444205,
"monthaverage":0.693495281755596
}
]
Into this format:
[
{
name: 'dayaverage',
data: [0.5, 0.146477031224456, 1.25559947299078, 0.799332962757087, 0.669041769041769, 0.656381486676017, 0.540495407737267]
},
{
name: 'weekaverage',
data: [1.33333333333333, 0.194758246723904, 1.43618513323983, 0.923262727610554, 0.67394482002558, 0.722973507315144, 0.576413277444205]
}, {
name: 'monthaverage',
data: [1.53571428571429, 0.601273296708939, 0.998426393184655, 0.769477297163179, 0.670944920469891, 0.69689774371321, 0.693495281755596]
}
].
All I'm doing is grouping the dayaverage, weekaverage and monthaverage values into an array and specifying what they are with a name key-value pair.
I'm having trouble writing this because the parent function is going to call with a list of criteria (for the above example it was : criteria = ['dayaverage', 'weekaverage', 'monthaverage'];) and that could change.
Any help appreciated, thanks
You could use an array for the wanted properties and build an array with the data upon.
function getGrouped(array, groups) {
var grouped = groups.map(function (a) {
return { name: a, data: [] };
});
array.personas.forEach(function (a) {
groups.forEach(function (k, i) {
grouped[i].data.push(a[k]);
});
});
return grouped;
}
var data = { personas: [{ category: "Persona1", month: 6, week: 24, day: 18, dayaverage: 0.5, weekaverage: 1.33333333333333, monthaverage: 1.53571428571429 }, { category: "Persona2", month: 6, week: 24, day: 18, dayaverage: 0.146477031224456, weekaverage: 0.194758246723904, monthaverage: 0.601273296708939 }, { category: "Persona3", month: 6, week: 24, day: 18, dayaverage: 1.25559947299078, weekaverage: 1.43618513323983, monthaverage: 0.998426393184655 }, { category: "Persona4", month: 6, week: 24, day: 18, dayaverage: 0.799332962757087, weekaverage: 0.923262727610554, monthaverage: 0.769477297163179 }, { category: "Persona5", month: 6, week: 24, day: 18, dayaverage: 0.669041769041769, weekaverage: 0.67394482002558, monthaverage: 0.670944920469891 }, { category: "Persona6", month: 6, week: 24, day: 18, dayaverage: 0.656381486676017, weekaverage: 0.722973507315144, monthaverage: 0.69689774371321 }, { category: "Persona7", month: 6, week: 24, day: 18, dayaverage: 0.540495407737267, weekaverage: 0.576413277444205, monthaverage: 0.693495281755596 }] };
console.log(getGrouped(data, ['day', 'dayaverage', 'weekaverage', 'monthaverage']));
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can do this using .map() along with .reduce() like so:
Also, to use dynamic properties, you can use bracket syntax ([]) for accessing properties on an object. Here, you can .map() your criteria list into the desired structure, and calculate the data using .reduce().
EDIT - Fixed resulting data structure to accurately output desired results
var personas = [{
"category": "Persona1",
"month": "6",
"week": "24",
"day": "18",
"dayaverage": 0.5,
"weekaverage": 1.33333333333333,
"monthaverage": 1.53571428571429
},
{
"category": "Persona2",
"month": "6",
"week": "24",
"day": "18",
"dayaverage": 0.146477031224456,
"weekaverage": 0.194758246723904,
"monthaverage": 0.601273296708939
},
{
"category": "Persona3",
"month": "6",
"week": "24",
"day": "18",
"dayaverage": 1.25559947299078,
"weekaverage": 1.43618513323983,
"monthaverage": 0.998426393184655
},
{
"category": "Persona4",
"month": "6",
"week": "24",
"day": "18",
"dayaverage": 0.799332962757087,
"weekaverage": 0.923262727610554,
"monthaverage": 0.769477297163179
},
{
"category": "Persona5",
"month": "6",
"week": "24",
"day": "18",
"dayaverage": 0.669041769041769,
"weekaverage": 0.67394482002558,
"monthaverage": 0.670944920469891
},
{
"category": "Persona6",
"month": "6",
"week": "24",
"day": "18",
"dayaverage": 0.656381486676017,
"weekaverage": 0.722973507315144,
"monthaverage": 0.69689774371321
},
{
"category": "Persona7",
"month": "6",
"week": "24",
"day": "18",
"dayaverage": 0.540495407737267,
"weekaverage": 0.576413277444205,
"monthaverage": 0.693495281755596
}
];
var criteria = ['dayaverage', 'weekaverage', 'monthaverage'];
function getMerged(objArr, criteria) {
var dataMap = objArr.reduce(function (result, current) {
criteria.forEach(function (elem) {
if (result[elem] != undefined) {
result[elem].push(current[elem]);
}
else {
result[elem] = [current[elem]];
}
});
return result;
}, {});
return criteria.map(function (elem) {
return {
name: elem,
data: dataMap[elem]
};
});
}
console.log(getMerged(personas, criteria));
One of the ways how to solve it, using Array#forEach.
var json = {personas:[{category:"Persona1",month:"6",week:"24",day:"18",dayaverage:.5,weekaverage:1.33333333333333,monthaverage:1.53571428571429},{category:"Persona2",month:"6",week:"24",day:"18",dayaverage:.146477031224456,weekaverage:.194758246723904,monthaverage:.601273296708939},{category:"Persona3",month:"6",week:"24",day:"18",dayaverage:1.25559947299078,weekaverage:1.43618513323983,monthaverage:.998426393184655},{category:"Persona4",month:"6",week:"24",day:"18",dayaverage:.799332962757087,weekaverage:.923262727610554,monthaverage:.769477297163179},{category:"Persona5",month:"6",week:"24",day:"18",dayaverage:.669041769041769,weekaverage:.67394482002558,monthaverage:.670944920469891},{category:"Persona6",month:"6",week:"24",day:"18",dayaverage:.656381486676017,weekaverage:.722973507315144,monthaverage:.69689774371321},{category:"Persona7",month:"6",week:"24",day:"18",dayaverage:.540495407737267,weekaverage:.576413277444205,monthaverage:.693495281755596}]},
criteria = ['dayaverage', 'weekaverage', 'monthaverage'],
arr = criteria.reduce(function(s,a){
s.push({name: a, data: []});
return s;
}, []);
arr.forEach(function(v) {
json.personas.forEach(function(c) {
v.data.push(c[v.name]);
})
})
console.log(arr);
try this:
var criteria = ['dayaverage', 'weekaverage', 'monthaverage']; //your dynamic criteria
var arr= []; //the filtered array you want
criteria.forEach(function(criterium){
// for each criterium you create a new object that you add to arr
arr.push({
name: criterium,
data: []
});
// then you populate the data field of the newly created field by browsing your big array "personas" that you need to parse before btw
personas.forEach(function (persona) {
arr[arr.length-1].data.push(persona[criterium]);
});
});
You can map the keys to an array of objects and map each of the objects' values by the current key in the mapping process.
var data = getData();
var modified = modify(data, 'personas', ['dayaverage', 'weekaverage', 'monthaverage']);
console.log(JSON.stringify(modified, null, 2));
function modify(data, root, keep) {
data = data[root] != null ? data[root] : data;
var keys = Object.keys(data[0]);
if (keep != null && keep.length > 0)
keys = keys.filter(key => keep.indexOf(key) > -1);
return keys.map(key => {
return {
name: key,
data: data.map(item => item[key])
}
});
}
function getData() {
return {
"personas": [{
"category": "Persona1",
"month": "6",
"week": "24",
"day": "18",
"dayaverage": 0.5,
"weekaverage": 1.33333333333333,
"monthaverage": 1.53571428571429
}, {
"category": "Persona2",
"month": "6",
"week": "24",
"day": "18",
"dayaverage": 0.146477031224456,
"weekaverage": 0.194758246723904,
"monthaverage": 0.601273296708939
}, {
"category": "Persona3",
"month": "6",
"week": "24",
"day": "18",
"dayaverage": 1.25559947299078,
"weekaverage": 1.43618513323983,
"monthaverage": 0.998426393184655
}, {
"category": "Persona4",
"month": "6",
"week": "24",
"day": "18",
"dayaverage": 0.799332962757087,
"weekaverage": 0.923262727610554,
"monthaverage": 0.769477297163179
}, {
"category": "Persona5",
"month": "6",
"week": "24",
"day": "18",
"dayaverage": 0.669041769041769,
"weekaverage": 0.67394482002558,
"monthaverage": 0.670944920469891
}, {
"category": "Persona6",
"month": "6",
"week": "24",
"day": "18",
"dayaverage": 0.656381486676017,
"weekaverage": 0.722973507315144,
"monthaverage": 0.69689774371321
}, {
"category": "Persona7",
"month": "6",
"week": "24",
"day": "18",
"dayaverage": 0.540495407737267,
"weekaverage": 0.576413277444205,
"monthaverage": 0.693495281755596
}]
};
}
.as-console-wrapper { top: 0; max-height: 100% !important; }

Get data from JSON object using value within

My JSON is as follows:
{
"sales": [{
"manager": "alberic",
"surgeon": "Dr Barry Biggins",
"amount": "300",
"country": "USA",
"percent-seller": "30",
"antiquity": "June 2017",
"date": "6"
}, {
"manager": "support",
"surgeon": "Dr Barry Biggins",
"amount": "300",
"country": "UK",
"percent-seller": "20",
"antiquity": "June 2017",
"date": "2"
}, {
...
}]
}
I want to retrieve the objects from sales where manager = "support" and date = "2". How do I go about this in jQuery?
Thanks!
Simply you can use filter() method and use your condition inside filter method function will return element if your condition become true otherwise it ignore element.
data= {"sales": [{
"manager": "alberic",
"surgeon": "Dr Barry Biggins",
"amount": "300",
"country": "USA",
"percent-seller": "30",
"antiquity": "June 2017",
"date": "6"
}, {
"manager": "support",
"surgeon": "Dr Barry Biggins",
"amount": "300",
"country": "UK",
"percent-seller": "20",
"antiquity": "June 2017",
"date": "2"
},
]
};
var matchedElements = data.sales.filter(function(element) {
return (element.manager == 'support' && element.date == '2');
});
console.log(matchedElements);
//if you want to access surgeon of first element of matchedElements
console.log(matchedElements[0].surgeon);
//if you want to access surgeon of all elements in matchedElements
for(i in matchedElements)
{
console.log(matchedElements[i].surgeon);
}
You filter the sales array.
Make sure to add the polyfill from the above link if you want to support older browsers.
var matchingSales = jsonData.sales.filter(function(sale) {
return sale.manager == 'support' && sale.date == '2';
});
var data = {
"sales": [{
"manager": "alberic",
"surgeon": "Dr Barry Biggins",
"amount": "300",
"country": "USA",
"percent-seller": "30",
"antiquity": "June 2017",
"date": "6"
}, {
"manager": "support",
"surgeon": "Dr Barry Biggins",
"amount": "300",
"country": "UK",
"percent-seller": "20",
"antiquity": "June 2017",
"date": "2"
}]
};
$.each(data.sales, function(i, v) {
if (v.manager == 'support' && v.date == '2') {
console.log(v.manager)
console.log(v.surgeon)
console.log(v.amount)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Iterate over them using .each()

how to remove of y -axis label in chart?

could you please tell me remove labels y axis labels .I make a simple chart using fusion library .
http://www.fusioncharts.com/dev/chart-attributes.html?chart=area2d
I saw some y axis label 0$,4$,12$..etc I want to remove that label .I need to show chart like this as shown in image [![enter image description here][1]][1]
http://jsfiddle.net/Tu57h/135/
can we show this on right side as shown in image ?
here is my code
http://jsfiddle.net/Tu57h/135/
FusionCharts.ready(function () {
var salesChart = new FusionCharts({
type: 'msarea',
renderAt: 'chart-container',
width: '450',
height: '300',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Sales of Liquor",
"subCaption": "Previous week vs current week",
"xAxisName": "Day",
"numberPrefix": "$",
"paletteColors": "#0075c2,#1aaf5d",
"bgColor": "#ffffff",
"showBorder": "0",
"showCanvasBorder": "0",
"plotBorderAlpha": "10",
"usePlotGradientColor": "0",
"legendBorderAlpha": "0",
"legendShadow": "0",
"plotFillAlpha": "60",
"showXAxisLine": "1",
"axisLineAlpha": "25",
"showValues": "0",
"captionFontSize": "14",
"subcaptionFontSize": "14",
"subcaptionFontBold": "0",
"divlineColor": "#999999",
"divLineIsDashed": "1",
"divLineDashLen": "1",
"divLineGapLen": "1",
"showAlternateHGridColor": "0",
"toolTipColor": "#ffffff",
"toolTipBorderThickness": "0",
"toolTipBgColor": "#000000",
"toolTipBgAlpha": "80",
"toolTipBorderRadius": "2",
"toolTipPadding": "5",
},
"categories": [
{
"category": [
{
"label": "jan 2015"
},
{
"label": "feb 2015"
},
{
"label": "mar 2015"
},
{
"label": "may 2015"
},
{
"label": "jun 2015"
},
{
"label": "jul 2015"
},
{
"label": "aug 2015"
},{
"label": "sep 2015"
},{
"label": "oct 2015"
}
,{
"label": "nov 2015"
},{
"label": "dec 2015"
}
]
}
],
"dataset": [
{
"seriesname": "Previous Week",
"data": [
{
"value": "13000"
},
{
"value": "14500"
},
{
"value": "13500"
},
{
"value": "15000"
},
{
"value": "15500"
},
{
"value": "17650"
},
{
"value": "19500"
}
]
}
]
}
})
.render();
});
What's shown on the right side of your image are trendlines. You can remove the y-axis labels with showYAxisValues: "0" in your chart setup, and add trendlines with:
"trendlines": [
{
"line": [
{
"startvalue": "12000",
"color": "#1aaf5d",
"valueOnRight": "1",
"displayvalue": "$12K"
}
]
}
]
fiddle here http://jsfiddle.net/Tu57h/138/
I'm not sure if the API offers such functionality. However, to hide the y-axis labels, you may target the section of the DOM created by the API and hide it.
setTimeout(function () {
$('#chart-container .fusioncharts-yaxis-0-gridlabels').eq(0).hide();
}, 50);
Fiddle : http://jsfiddle.net/Tu57h/137/ ( I couldn't get it working on jsfiddle but it works fine when running on local machine).

JSON iterating through objects and accessing data result to cannot read property of undefined

I'm parsing a json from a website and trying to get some data from it. However, it is giving me undefined values when iterating through a collection of objects. If it's a badly formatted json, unfortunately, I can't change it.
[
{
"startYear": 2014,
"startMonth": 6,
"startDay": 31,
"endYear": 2014,
"endMonth": 7,
"endDay": 29,
"selectedDate": "2014_7_8",
"departureStation": "Manila",
"arrivalStation": "Boracay (Caticlan)",
"departureStationCode": "(MNL)",
"arrivalStationCode": "(MPH)",
"departureLabel": "DEPARTURE",
"arrivalLabel": "RETURN",
"dateMarketHash": {
"date_0_2014_6_31": {
"containerId": "date_0_2014_6_31",
"fromLabel": "From",
"currency": "PHP",
"price": null,
"formattedDate": "Thu, Jul 31, 2014",
"year": "2014",
"month": "6",
"day": "31",
"points": null,
"pointsSuffix": "",
"pointsLabelAppend": ""
},
"date_0_2014_7_1": {
"containerId": "date_0_2014_7_1",
"fromLabel": "From",
"currency": "PHP",
"price": 1929,
"formattedDate": "Fri, Aug 01, 2014",
"year": "2014",
"month": "7",
"day": "1",
"points": 0,
"pointsSuffix": "",
"pointsLabelAppend": ""
}
}
},
{
"startYear": 2014,
"startMonth": 7,
"startDay": 24,
"endYear": 2014,
"endMonth": 8,
"endDay": 23,
"selectedDate": "2014_8_8",
"departureStation": "Boracay (Caticlan)",
"arrivalStation": "Manila",
"departureStationCode": "(MPH)",
"arrivalStationCode": "(MNL)",
"departureLabel": "DEPARTURE",
"arrivalLabel": "RETURN",
"dateMarketHash": {
"date_1_2014_7_24": {
"containerId": "date_1_2014_7_24",
"fromLabel": "From",
"currency": "PHP",
"price": 3079,
"formattedDate": "Sun, Aug 24, 2014",
"year": "2014",
"month": "7",
"day": "24",
"points": 0,
"pointsSuffix": "",
"pointsLabelAppend": ""
},
"date_1_2014_7_25": {
"containerId": "date_1_2014_7_25",
"fromLabel": "From",
"currency": "PHP",
"price": 3079,
"formattedDate": "Mon, Aug 25, 2014",
"year": "2014",
"month": "7",
"day": "25",
"points": 0,
"pointsSuffix": "",
"pointsLabelAppend": ""
}
}
}
]
my code:
// Printing the value of 'day' from each 'dateMarketHash'
for (i = 0; i<json.length; i++)
{
var current = json[i].dateMarketHash;
for(var key in current){
if (current.hasOwnProperty(key)) {
document.write(current.key.day); // Cannot read property 'day' of undefined
}
}
}
No, it is the fact that you are reading "key" and not the variable. You need to use bracket notation, not dot notation.
document.write(current[key].day);
And you should not be using document.write.

Categories