when executing the following code firebug tells me: values[this.geo.value] is undefined
what is the problem?
$.get('./RDFexamples/tin00089_test2.rdf', null, function (rdfXml) {
var rdf, json = {};
var values = new Array();
rdf = $.rdf()
.load(rdfXml)
.prefix('', 'http://ontologycentral.com/2009/01/eurostat/ns#')
.prefix('qb', 'http://purl.org/linked-data/cube#')
.prefix('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#')
.prefix('dcterms', 'http://purl.org/dc/terms/')
.prefix('sdmx-measure', 'http://purl.org/linked-data/sdmx/2009/measure#')
.where('?observation a qb:Observation')
.where('?observation dcterms:date ?date')
.where('?observation sdmx-measure:obsValue ?measure')
.where('?observation :geo ?geo')
.each(function () {
values[this.geo.value].push(this.measure.value);
//alert(this.date.value)
//alert(this.measure.value)
//alert(this.geo.value)
}
);
alert(values);
});
values[this.geo.value] is never initialized so you can't do .push because values[this.geo.value] is undefined, you first need to create an array in values[this.geo.value] before you can push things into it.
Pseudo-code example
if values[this.geo.value] == undefined {
values[this.geo.value] = []
}
values[this.geo.value].push(...)
push is a method of the Array object itself - you are calling it on a value within the Array (which has probably not been set, hence 'undefined'). It's unclear what this.geo.value is, but assuming its the index of the array item you are trying to set, your options are:
values.push(this.measure.value);
or
values[this.geo.value] = this.measure.value;
Related
Json Array Object
Through Ajax I will get dynamic data which is not constant or similar data based on query data will change. But I want to display charts so I used chartjs where I need to pass array data. So I tried below code but whenever data changes that code will break.
I cannot paste complete JSON file so after parsing it looks like this
[{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
You can use Object.keys and specify the position number to get that value
var valueOne =[];
var valueTwo = [];
jsonData.forEach(function(e){
valueOne.push(e[Object.keys(e)[1]]);
valueTwo.push(e[Object.keys(e)[2]]);
})
It seems like what you're trying to do is conditionally populate an array based the data you are receiving. One solution might be for you to use a variable who's value is based on whether the value or price property exist on the object. For example, in your forEach loop:
const valueOne = [];
jsonData.forEach((e) => {
const val = typeof e.value !== undefined ? e.value : e.average;
valueOne.push(val);
})
In your jsonData.forEach loop you can test existence of element by using something like:
if (e['volume']===undefined) {
valueone.push(e.price);
} else {
valueone.push(e.volume);
}
And similar for valuetwo...
You could create an object with the keys of your first array element, and values corresponding to the arrays you are after:
var data = [{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
var splitArrays = Object.keys(data[0]).reduce((o, e) => {
o[e] = data.map(el => el[e]);
return o;
}, {});
// show the whole object
console.log(splitArrays);
// show the individual arrays
console.log("brand");
console.log(splitArrays.brand);
console.log("volume");
console.log(splitArrays.volume);
// etc
Hi there before I start I did try looking through the search about writing variables so if this has been asked and answered then I do apologise but this is baffling me ....
So here goes ..
example of what I am talking about
var i = e[ab]
var n = e[cd][ef]
var t = e[cd][gh]
I know that when I want var i I can put e.ab but how would I go about writing var n and var t
So assuming your object looks like this (based on your description, it sounds like you want to access an object which is the property of another object), and you want to access them through the indexer properties (which would be a property of a property).
var e = {
ab : "variableOne",
cd : {ef:"ef object"},
gh : {ij:"ij object"},
}
var i = e["ab"]
//if these are properties, then you need to add quotes around them
//to access a property through the indexer, you need a string.
var n = e["cd"]["ef"]
var t = e["gh"]["ij"]
console.log(i);
console.log(n);
console.log(t);
console.log("this does the same thing:")
console.log(e.ab);
console.log(e.cd.ef);
console.log(e.gh.if);
In your example the object would look like
//e is the parameter, but I show it as a variable to show
// it's relation to the object in this example.
e = {
now_playing: {artist:"Bob Seger"; track:"Turn the Page"}}
}
this is different than an array of arrays:
var arr = [
['foo','charlie'],
['yip', 'steve'],
['what', 'bob', 'jane'],
];
console.log(arr[0][0]); //foo
console.log(arr[0][1]); //charlie
console.log(arr[1][0]); //yip
console.log(arr[1][1]); //steve
console.log(arr[2][2]); //jane
https://jsfiddle.net/joo9wfxt/2/
EDIT:
Based on the JSON provided, it looks like parameter e in the function is assigned the value of the item in the array. With your code:
this line will display: "Rock you like a hurricane - Nontas Tzivenis"
$(".song_title .current_show span").html(e.title);
and this line will display: "Rascal Flatts - Life is a Highway".
$(".song_title .current_song span").html(e.np);
If it's not displaying you might want to double check your JQuery selectors. This ".song_title .current_song span" is selecting it by the classes on the element.
I think you are in need of a bit of a refresher on basic JavaScript syntax. Here's how you can assign an "empty object" to a variable, then start to assign values to it's properties:
e = {}
e.ab = {}
e.cd = {}
e.cd.ef = "data"
or you can use the associative array syntax for property access:
e = {}
e["ab"] = {}
e["cd"] = {}
e["cd"]["ef"] = "data"
You see the latter is using the object e like a two-deep associative array. Is that what you are looking to do?
JavaScript is not strongly typed. So an Array "a" could contain objects of different types inside.
var a = [ "a value", [1, 2, 3], function(){ return 5 + 2;}];
var result = a[0]; //get the first item in my array: "a value"
var resultOfIndexedProperty = a[1][0]; //Get the first item of the second item: 1
var resultOfFunc = a[2](); //store the result of the function that is the third item of my array: 7
Hope this helps a little.
var $scope={};
var componentsDir="/root/";
var appPrefix="/app/";
var scriptRef=[];
function proDir(scriptName){
return componentsDir+appPrefix+'-home-components/pro/js/'+scriptName+'.js';
};
var scriptList =[
{s_name:'jquery',file:"jquery.js"},
{s_name:'bootstrap',file:"bootstrap.min.js"},
{s_name:'easing',file:"jquery.easing.min.js"},
{s_name:'fittext',file:"jquery.fittext.js"},
{s_name:'wow',file:"wow.min.js"},
{s_name:'creative', file:"creative.js"},
/*{bootstrap :"bootstrap.min.js"},
{easing :"jquery.easing.min.js"},
{fittext :"jquery.fittext.js"},
{wow :"wow.min.js"},
{creative :"creative.js"},*/
]
var newscript = scriptList.map(function(scriptItem){
console.log(scriptItem)
return {{scriptItem.s_name:'jquery'},{scriptItem.file:proDir(scriptItem.file)}},
});
console.log(newscript)
I try to find a way to loop through a list of script and add extra dir info to each element with .map. But I am getting an error of
Uncaught SyntaxError: Unexpected token {
I try to return each element as a object for the new newscript array
{ is not a valid character after { in JSON.
replace this line:
return {{scriptItem.s_name:'jquery'},{scriptItem.file:proDir(scriptItem.file)}}
with this line:
return {"scriptItem.s_name": 'jquery', "scriptItem.file": proDir(scriptItem.file)}
or another variant might be:
return {
scriptItem: {
s_name: 'jquery',
file: proDir(scriptItem.file)
}
};
Here is the variant you asked for with your comment "I want to access the newscript's location value like this : newscript.jquery":
var newscript = scriptList.map(function(scriptItem) {
var returnval = {};
returnval[ scriptItem.s_name ] = scriptItem.file;
return returnval;
});
I think you are bumping up against this issue:
How can i name object "keys" programmatically in JavaScript?
When in doubt:
http://jsonlint.com/
The map() method creates a new array with the results of calling a provided function on every element in this array.
This means that the scriptItem variable in each map iteration is one of the objects you have in your scriptList array. Map() makes an operation on that variable, and returns a new variable that will be pushed in a new array, that scriptItem will point to.
In your code, you are returning 2 objects, instead of one. But each array element can hold only one object. So, return only one thing.
var newscript = scriptList.map(function(scriptItem){
console.log(scriptItem)
return {s_name:'jquery', file:proDir(scriptItem.file)}
});
This should do the work for you:
var newscript = scriptList.map(function(scriptItem){
console.log(scriptItem);
var name = scriptItem.s_name;
var file = proDir(scriptItem.file);
return {s_name: name, file:file}
});
I have the code shown below.
My problem is: the part console.log(obj) is saying that Object {InternalNumber = 22 } and leaving out all the other variables.
I am expecting it to say:
Object { Id = someID, ParameterId="someParaId", InternalNumber = someNr, value="someValue"}
What might be wrong?
If you haven't noticed... I am saving the object to localStorage, and then retrieving it from there.
function getModel() {
var model = {
Id: '',
ParameterId: '',
InternalNumber: '',
Value: ''
}
return model;
}
function saveObjectToLocal() {
model = getModel();
model.Id = $(this).find(':input[name$=Id]').val();
model.ParameterId = $(this).attr('id');
model.InternalNumber = currentParcel.children('#viewModel_InternalNumber').val();
model.Value = $(this).find(':input[name$=Value]').val();
localStorage.setItem("model", JSON.stringify(model));
}
function getObjectFromLocalAndInsertInFields() {
obj = JSON.parse(localStorage.getItem("model"));
console.log(obj);
}
How are you calling saveObjectToLocal function. $(this) inside of that function is probably not matching anything because "this" is probably the global (window) object, and DOM elements aren't matched within the window object.
To see what I'm talking about. Run:
$(this);
$(this).find("input");
$(this).find("input").attr("id");
from your console. The first output will be length 1 of just window, the second would be an empty jQuery object, and the third would be undefined.
Calling .val() and .attr on an empty jQuery list would be undefined and therefore not serialized to JSON. InternalNumber is serialized because currentParcel.children is giving a match. You need to fix the $(this) selectors.
Json stringify function will exclude attributes with undefined value, so check first if the missing attributes have values
So close to nailing this but falling at the last hurdle... Need some clarification.
Basically, I want to load in the array value of a key in a given object as a variable, if other variable strings match.
Perhaps it's better if I give it some context:
js:
var ArraysObject = {
"new" : [
"http://productPageBanners/UK/2new/c0bkn201001u0000.jpg",
"http://productPageBanners/UK/2new/h0ihd60100000001.jpg",
"http://productPageBanners/UK/2new/l0flj20100000001.jpg",
"http://productPageBanners/UK/2new/m0lrt60100000001.jpg",
"http://productPageBanners/UK/2new/p0gps50106000001.jpg"
],
"knives" : [
"http://productPageBanners/UK/3aknives/c0bkn201001u0000.jpg",
"http://productPageBanners/UK/3aknives/n01pl20100000001.jpg"
]
};
var url = jQuery(location).attr('href'); // get the current url, outputs URL
var icatRef = url.split("/")[4]; // capture the icatRef from url, outputs ==>"knives"
// Get properties on the object ArraysObject as an array
var icatTitlesInObject = Object.keys(ArraysObject); // outputs the keys in object, i.e ==> ["new","knives"]
Then I want to check that if the indexOf that array is equal to the icatRef (pulled from the URL), then create a new variable which stores the relevant array from the correct key.
Something like:
if (icatsArray.indexOf() == icatRef) {
var currentarraytorandomise = ArraysObject.keys.this};
// if "knives" is the icatRef then currentarraytorandomise ==> [
// "http://productPageBanners/UK/3aknives/c0bkn201001u0000.jpg",
// "http://productPageBanners/UK/3aknives/n01pl20100000001.jpg"
// ]
However that last bit is wrong because currentarraytorandomise is undefined.
I hope that's clear! Quite new to OOP.
You're using indexOf incorrectly, try something like this:
var currentarraytorandomise, index = icatsArray.indexOf(icatRef);
if (index >= 0) {
currentarraytorandomise = ArraysObject[icatsArray[index]];
}
But you could just try to get the array directly:
ArraysObject[icatRef]
Without extracting keys or anything. If icatRef doesn't exist, you'll get undefined.