trying to make this as simple to understand as possible...
I have a JS function that essentially picks which array (a list) a person has selected and then passes it to another function to then print that array out. The problem is I can't figure out how to use the array name that I have passed take a look:
Arrays:
var allLists =['list1', 'list2'];
var list1 = ['orange', 'pear', 'apple'];
var list2 = ['car', 'plane', 'bike'];
Function to loop through the lists:
function printAllLists() {
lists.forEach(function(entry) {
count++;
document.write("<h2> List Number " + count + "</h2>");
printList(entry);
});
}
Function to output each list contents to a table
function printList(listname) {
document.write("<table>");
document.write("List Name Is: " + listname);
listname.forEach(function(entry) { //HERE IS THE PROBLEM
document.write("<tr><td>");
document.write(entry);
document.write("</td></tr>");
});
document.write("</table>");
}
The problem I have is the line below literally uses "listname" rather than what has been passed as list name which should be either "list1" or "list 2"
listname.forEach(function(entry) {
So it just fails with this error. How can I get it to swap the name of the array instead. Sorry if its not really clear what I'm trying to say I'm not sure how to exactly word this (which is probably why google isn't helping.)
Uncaught TypeError: listname.forEach is not a function
JSFiddle
Link to JSFiddle - https://jsfiddle.net/38x5nw62/
Thanks
Do it like this:
var list1 = ['car', 'plane', 'bike'];
var list2 = ['car', 'plane', 'bike'];
var allLists = [list1, list2];
Working Code here: https://jsfiddle.net/38x5nw62/1/
You where using var allLists = ['list1', 'list2']; wich does only contain strings 'list1' and 'list2', NOT the variables/arrays named smiliarly to the strings.
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?
How to split an object into array of objects based on a condition.
oldObject = {"Chicago, IL:Myrtle Beach, SC": 0.005340186908091907,
"Portsmouth, NH:Rock Hill, SC": 0.0063224791225441205,
"Columbia, SC:Laconia, NH": 0.006360767389277389,
"Council Bluffs, IA:Derry, NH": 0.0016636141225441225}
Above is the given sample object. I want to make an array of objects like this,
newArray = [{"city":"Chicago", "similarTo":"Myrtle"},
{"city":"Portsmouth", "similarTo":"Rock Hill"},
{"city":"Columbia", "similarTo":"Laconia"},
{"city":"Council Bluffs", "similarTo":"Derry"}]
I have been scratching my head with this for a while now. How can I get the above array(newArray)?
Here is a bunch of code you can try.
1) Iterate over oldObject and get the name of the property.
2) Split that name into an array based on the ":" character, since it separates the cities
3) Go over that new array, splitting it on the "," character (so as not to get the states).
4) Put the values into the newObject, based on whether it's the first or second part of the original property name.
5) Push that newObject, now with items, into a newArray.
Basically, this parses apart the name and does some array splitting to get at the right values. Hope it helps and helps you understand too.
var oldObject = {"Chicago, IL:Myrtle Beach, SC": 0.005340186908091907,
"Portsmouth, NH:Rock Hill, SC": 0.0063224791225441205,
"Columbia, SC:Laconia, NH": 0.006360767389277389,
"Council Bluffs, IA:Derry, NH": 0.0016636141225441225};
var newArray = [];
for (object in oldObject) {
var thisObjectName = object;
var thisObjectAsArray = thisObjectName.split(':');
var newObject = {
'city': '',
'similar_to': ''
};
thisObjectAsArray.forEach(function(element,index,array) {
var thisObjectNameAsArray = element.split(',');
var thisObjectNameCity = thisObjectNameAsArray[0];
if(index===0) {
newObject.city = thisObjectNameCity;
} else if(index===1) {
newObject.similar_to = thisObjectNameCity;
}
});
newArray.push(newObject);
}
console.log(newArray);
PS: to test, run the above code and check your Developer Tools console to see the new array output.
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 making string contains values. I have company name, product and its value. I want to store these value in string but if user choose same product of same company then I want to only append product no only.
current string value TATA#434#tyre,TATA#234#door,TATA#687#tyre, and it should be as
TATA#434,687#tyre,TATA#234#door
as we can see user choose same company with same production, only product no. is different so we need to append only product no.
if customer choose all four product then string should be read like this
TATA#434,687#tyre,TATA#234#door,Maruti#8776#door
company and product can be increase. also in last entry how to remove ",".
Here is attached fiddle.
Code
var str="";
$('a').click(function(){
var el= $(this).parent();
str += el.find('#brand').text() + "#" + el.find('#no').text() + "#" + el.find('#product').text() +",";
console.log(str)
})
My real advice would be to use an object. Why? Because it makes your data manipulation SO much easier my friend.
Use something like:
function car(val1,val2,val3,val4) {
this.val1 = val1;
this.val2 = val2;
this.val3 = val3;
this.val4 = val4;
}
Now we can just make one with:
var item1 = new car("TATA#434","687#tyre","TATA#234#door","Maruti#8776#door");
Now you can change whatever you want.
If you would like further guidance on how to display this in the format you've suggested, more than happy to help.
Your solution involves many RegEx... which can turn sour quickly. As a large scale developer, I advice against this if there is any chance your values will change format in the future.
Using Arrays:
Here is a use case:
http://jsfiddle.net/k6XFy/1/
var a = ["TATA#434","687#tyre","TATA#234#door","Maruti#8776#door"];
function display(x){
alert(x);
}
alert(a[1]);
a[1] = "Convert";
alert(a[1]);
alert(a);
Edit:
You can join the array like so:
var a = ["TATA#434","687#tyre","TATA#234#door","Maruti#8776#door"];
function display(x){
alert(x);
}
var b = a.join(',');
alert(b);
View here: http://jsfiddle.net/k6XFy/3/
Why would you not store it in an object?
This is how I would store it.
{TATA: { 434: 'tyre', 234: 'door' }, Maruti: { 8776: 'door' }}
If you need to use it as a string, loop through it constructing the string when you need it.
EDIT:
I'm not sure the exact context, but perhaps this would even make sense:
{TATA: { tyre: [434,687], door: [234] }, Maruti: { door: [8776] }}
or
{ tyre: { TATA: [434,687] }, door: { Maruti: [8776], TATA: [234] }}
var Animals = {
"Europe": { "weasel.jpg": "squeak", "cow.jpg": "moo"},
"Africa": { "lion.jpg": "roar", "gazelle.jpg": "bark"},
};
function region(a){
var b = "Animals."+a;
for(var index in b) {
var target = document.getElementById('div1');
var newnode = document.createElement('img');
newnode.src = index;
target.appendChild(newnode)
}
}
RELEVANT HTML
<li onclick="europe('Europe')">Europe</li>
Goal: on the click of the Europe <li>, pass the word Europe into my region function where it is then concatenated to produce Animals.Europe
This is in order to identify an array within the object structure at the top using the for(var index in Animals.Europe) loop. Why is the concatenation which produces Animals.Europe not treated in the same way as if I had typed this out?
In addition, you can see that I have used arrays to store an image source and description for different animals. Using my limited coding knowledge this was all I could think of. Is there an easier way to store image/description data in order to produce in HTML?
"Animals." + a is just a string value, e.g. "Animals.Europe", which is not the same thing as Animals.Europe. If you change the first line to var b = Animals[a];, you should be all set.
Edit: and as elclanrs pointed out, it should be region('Europe'), not europe('Europe').
Why is the concatenation which produces Animals.Europe not treated in the same way as if i had typed this out?
In this case the variable b is just a string ("Animals.Europe"), which is treated like any other string (i.e. a list of characters). This means that when you attempt to loop through it (for(index in b)) you will be looping over a simple list of characters.
What you can do instead is use the square brace notation of accessing an objects properties. This means you can instead write var b = Animals[a], retrieving attribute a from Animals. You can read more about working with objects in this way on this MDN page
You can access the europe property using the following
Animals[a]
Also you're calling a "europe" function when you should be calling "region"
You're not storing animals in arrays here, but in objects with the image names as keys. Usually you'll want to use relevant names as keys. For example if you want arrays of animals for each continent
var Animals = {
"Europe": [{
imageSrc: "weasel.jpg",
cry: "squeak"
},{
imageSrc: "cow.jpg",
cry: "moo"
}],
"Africa": [{
imageSrc: "lion.jpg",
cry: "roar"
},{
imageSrc: "gazelle.jpg",
cry: "bark"
}]
};
Now Animals['Europe'] gives an array of objects, where you could eventually store other properties. So if b is an array your loop will now look like:
var b = Animals['Europe'];
for(var i=0; i < b.length; i++) {
var target = document.getElementById('div1');
var newnode = document.createElement('img');
var animalData = b[i]; // The array item is now an object
newnode.src = animalData.imageSrc;
target.appendChild(newnode)
}