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}
});
Related
I need one help. I need to insert one new value into existing array by matching the key value using Javascript.I am explaining the scenario below.
var galArr=[
{'image':'12.png','comment':'hii','act':'edit'},
{'image':'13.png','comment':'hello','act':'edit'},
{'image':'14.png','comment':'hee','act':'edit'},
]
The above is my existing array.I need to match with the below another array.
var arr=[
{'image':'12.png','comment':'hii'},
{'image':'14.png','comment':'hee'},
]
Here i need to match the array arr with an array galArr if image name will same this checked:true will add in the rective row of existing array galArr. Suppose arr[0].image==galArr[0].image then checked:true will add in that respective row of existing array. Please help me.
This should be sufficient.
var galArr=[
{'image':'12.png','comment':'hii','act':'edit'},
{'image':'13.png','comment':'hello','act':'edit'},
{'image':'14.png','comment':'hee','act':'edit'},
];
var arr=[
{'image':'12.png','comment':'hii'},
{'image':'14.png','comment':'hee'},
];
// start looping over `arr`
arr.forEach(function(o, i){
// now loop over `galArr` to find match
galArr.forEach(function(gO, i){
// when there is a match
if(o.image == gO.image){
console.log(gO);
// add checked property to this object
gO['checked'] = true;
}
});
});
// Output
console.log(galArr);
First of all check condition and if the condition match then create a new temp json and replace it with old json
arr.forEach(function(d){
galArr.forEach(function(e){
if(e.image==d.image){
temp = {};
temp.image = e.image;
temp.comment = e.comment;
temp.checked = e.comment;
temp.action = e.action;
e = temp;
}
});
});
I would create an image index, where its indexes would be the whole image file names and later I would use that image index to quickly check and add checked property to galArr array:
var galArr=[
{'image':'12.png','comment':'hii','act':'edit'},
{'image':'13.png','comment':'hello','act':'edit'},
{'image':'14.png','comment':'hee','act':'edit'},
];
var imageIndex = galArr.map(function(item) {
return item.image;
});
var arr=[
{'image':'12.png','comment':'hii'},
{'image':'14.png','comment':'hee'},
]
arr.forEach(function(item) {
item.checked = imageIndex.indexOf(item.image) > -1;
});
If your users will use your JavaScript code within a modern Web browser, I would use the new Set collection:
var galArr=[
{'image':'12.png','comment':'hii','act':'edit'},
{'image':'13.png','comment':'hello','act':'edit'},
{'image':'14.png','comment':'hee','act':'edit'},
];
var imageIndex = galArr.reduce(function(result, item) {
result.add(item.image);
return result;
}, new Set());
var arr=[
{'image':'12.png','comment':'hii'},
{'image':'14.png','comment':'hee'},
]
arr.forEach(function(item) {
item.checked = imageIndex.has(item.image);
});
I've asked a question to assist everyone in understanding how valueable are sets: Is Set a hashed collection in JavaScript?
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.
I am building JavaScript code to make a custom push function. My new function should act exactly like the original push function.
Here is the code. Please check it.
<script type="text/javascript">
function MyArray(){
this.add=function(x){
return this[this.length]=x;
}
}
MyArray.prototype=Array.prototype;
var collection = new MyArray();
collection.push(44);
collection.add(56); // this is not working.
collection.push(77);
collection.push(88);
console.log(collection);
</script>
Because you're not using a native array, the length property doesn't automatically adjust itself. You need to increment it manually, otherwise the next push will just overwrite it:
function MyArray(){
this.add=function(x){
return this[this.length++]=x;
}
}
If you want to use add instead of push (so, use add as push-alias), just refer to the original Array.prototype.push. See snippet. The snippet also contains a custom addMulti method, derived from Array.prototype.push.
function MyArray(){ }
MyArray.prototype = Array.prototype;
MyArray.prototype.add = Array.prototype.push;
// custom addMulti method, derived from Array.prototype.push
MyArray.prototype.addMulti = function addMulti(arrayOfValues){
[].push.apply(this, arrayOfValues);
};
var foo = new MyArray;
// add and push both work
foo.add(13);
foo.push(17);
foo.add(15,16,18);
foo.push(112);
// push an array of values
foo.addMulti([200,300,400,500]);
var report = new MyArray;
report.add('<code>foo.length: ',foo.length, ', foo: [', foo, ']</code>');
document.querySelector('#result').innerHTML = report.join('');
<div id="result"><div>
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.
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;