Displaying each item in a JS Array separately [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am trying to get Javascript Array to display each group name and group ID on its own line instead of sending the whole array to the next script. Essentially what would be desired is that the group ID and Group Name gets pushed "foreach" to the next script that will use those ids to generate a tab. I have the tab generation done and the data import done, the only thing I cant figure out is how to get the array to display each item separately.
Here is my current code:
$.getJSON("inc/load.php", function(data){
for (var i = 0, len = data.length; i < len; i++) {
var Names = data.group_name[i];
var GroupID = data.group_id[i];
console.log(Names + " " + GroupID)
}
I have searched on here and google and have not found a solution.
EDIT
The data does load information correctly, when you use
console.log(data[i]); it returns this style information in the console log:
Object {group_id: "556336557801913", group_name: "How to Start a Startup"}
Object {group_id: "1448816275428542", group_name: "ARK: Survival Evolved"}
Object {group_id: "286255764917755", group_name: "VIP BUYER ADVANTAGE MEMBER"}
What I would like the end result to be is to take the Group_Id and the Group_name put each into its own variable and then pass those variables to another function. And then repeat for the next item in the array.
Im sorry I am still new to Stackoverflow and learning how to best construct my questions.

Edit:
Rather than using for-in as Paul Rob rightly pointed out, you might just correct the following in your code for a start and that might sort you out.
var Names = data[i].group_name;
var GroupID = data[i].group_id;
End Edit
I think what you want is:
for (var i in data) {
var Names = data[i].group_name;
var GroupID = data[i].group_id;
console.log(Names + " " + GroupID);
}
Don't ask me why i is the index rather than the item, one of those nuances of javascript you just grow to live with and love :)

Related

How to put an object property in a variable? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
var info = [
{'user': 'person1','location': "NY"},
{'user': 'person2','location': "NJ"},
{'user': 'person3','location': "NC"}
];
var text="";
for (var i=0; i<=2; i++) {
text+='<div id="box" onclick="alertMe()">'+ info </div>';
}
function alertMe(){
var val = info[location];
alert(val);
}
This is focused on the function alertMe() part. I'm trying to put each location in one variable so when the user clicks on one, it will show an alert with the specific location.
There is a few things that are not going to work with your code.
The variable location is not defined.
If you are trying to access the property location or your object, it might not work that way because info is an array. You could access info like so info[0] but not via the key location since it does not exist.
From what I undestand, you want to show the currently clicked location. Your alertMe function has no way to know which location has been clicked.
Not a problem but a suggestion, you might want to use let or const rather than val, here is why.
You are never adding your HTML string to the DOM, so nothing is appearing.
You are missing a ' in your string.
You are trying to show the variable info in the tag div in your html, yet info is an array of objects.
With that in mind, here is a revised version of your code. Please try to understand what's going on rather than copy pasting this into your project.
var info = [
{'user': 'person1','location': "NY"},
{'user': 'person2','location': "NJ"},
{'user': 'person3','location': "NC"}
];
let text = "";
for (var i=0; i<=2; i++) {
const currentLocation = info[i];
text+= `<div id="box" onclick="alertMe(${i})">${currentLocation.location}</div>`;
}
document.write(text)
function alertMe(index){
const val = info[index].location;
alert(val);
}
In this snippet, you can see that i've replace a few things.
The alertMe function now take an index as an argument. Which will represent the index being clicked.
I'm creating a new variable in my for loop for the current info element.
I'm using this new variable to print the location.
I'm accessing the clicked location via it's index rather than the innexisting location variable.
I've replaced your string building with string template. Not necessary but cool.
It doesn't work, because you're trying to access a property of an object in an array.
if you had:
const info = {'user': 'person1','location': "NY"}
then info['location'] would work.
The way you have it you need to point to the relevant item of the array first:
var info = [
{'user': 'person1','location': "NY"},
{'user': 'person2','location': "NJ"},
{'user': 'person3','location': "NC"}
];
let myLocation = info[0]['location']
where 0 is the index of tfirst element of the array.

How to find that particular array Item is present or not Using JQuery + Backbone.js [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Each ArrayItem contains no. of Property like Id, Name, Description etc
But we want to Fetch ArrayItem with Help of Name Property .
So Please give me code suggestion in Jquery or backbonejs without using for loop.
If you are using BackboneJS, you already have UnderscoreJS installed. Underscore has several methods for searching through a collection. For instance, using _.findWhere(...):
var myArray = [ ... ];
var helpItem = _.findWhere(myArray, { name: 'help' });
This would return the first entry in the array that has a name property equal to 'help'. _.findWhere(...) can match multiple properties too. If you want to find an item with something other than direct equality of properties, you can use _.find(...):
var overTwentyOne = _.find(myArray, function(entry) {
return entry.age > 21;
});
This would return the first entry in the array whose age property was greater than 21.
Note also that most of the list-centric methods in Underscore are automatically mixed into all Backbone.Collection instances. So if you were searching through a Collection, the above findWhere(...) example could be more simply written as:
var helpItem = collection.findWhere({ name: 'help'});
This would return the first Backbone.Model instance from collection that had a property name equal to help.

Javascript HTML localstorage [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I use localstorage to save items (songs) as favorites. But I would also like to be able to remove the items from the array, so not the key but the value of the key.
for example I have the key Songs and values of one , two, three. I would like to be able to remove two from Songs but one and three should remain.
I cant seem to figure out how to do so because all I can find is how to remove the key and not the value of the key.
Since you don't have any source code on display I will give you quick example of how to remove single values from the clients Local Storage. You can expand on this to remove multiple values. Wouldn't want to remove all the fun
I have commented out the Localstoage and created a Songs array so this will work in the snippet.
Remove /* and */ to uncomment that section and change getItem('Songs') to fit your current source code.
You will also want to remove var Songs[]; Snippet Use only
/*--Local Storage Use
// Get Songs from Local Storage
var Storage = localStorage.getItem('Songs');
//Split Songs into an Array
var Songs=Storage.split(',');
*/
// Snippet Use -- Example Values of the Songs Result
var Songs = ['Song One', 'Song Two', 'Song Three','Song Four'];
//------ Remove Single Value
var Remove = Songs.indexOf('Song Two');
alert('Old Songs List:\n'+Songs);
if (Remove > -1) {
Songs.splice(Remove, 1);
}
alert('New Songs List:\n'+Songs);
//--Update LocalStorage
//localStorage.setItem('Songs',Songs);
If you have any questions about the above example please leave a comment below and I will get back to you as soon as possible.
I hope this helps. Happy coding!
Assuming your Object is structured like this;
"Songs": ["Song One", "Song Two", "Song Three"]
I don't have the code for you, but the process I would go through is;
Read localStorage item (localStorage.getItem('Songs'))
If you know the index of the item, you can then remove it. See this post for details
Re-save the Object to localStorage (localStorage.setItem('Songs', SongsObj)).
You need to get value of localStorage (Songs for example). Save value into variable, then change value (delete/remove some list items), then uses same key (Songs) set previous localStorage key with new value.
localStorage.setItem('Songs', [1,2,3,4,5]);
var songs = localStorage.getItem('Songs');
// ... some operations with list...
songs = [1,3,4];
localStorage.setItem('Songs', songs);

Extra tags on the end of a URL for different pages [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Hello I really want to learn how to do something like this. If you go to a page for example it says http://example.net/search.html?catagory=food&includelevelone=true. I do not have access to php so it can only be HTML and Javascript/jQuery. Thanks in advance!
The part of the URL that is from the questionmark onwards is called a query string.
Here is a pure JavaScript function to parse the query string to obtain particular values:
function querystring(key)
{
var filter;
var value;
key = key.replace(/[\[]/, '\\\[').replace(/[\]]/, '\\\]');
filter = new RegExp('[\\?&]' + key + '=([^&#]*)');
value = filter.exec(window.location.search);
if(value == null)
{
return '';
}
else
{
return decodeURIComponent(value[1].replace(/\+/g, ' '));
}
}
You just pass in the query string key name you're interested in (as a string) and you get the value back (also as a string.) An example of how you could use the function:
alert('Category = ' + querystring('catagory'));
Everything behind the questionmark is a url parameter. every word left of an equal sign is the name of the parameter, everything right of an equal sign is the corresponding value. The name-value-pairs are divided by &-signs
Here are two pages i quickly googled that are about getting these parameters in JavaScript (wich is really not that hard):
http://code-tricks.com/get-url-parameters-using-javascript
http://ziemecki.net/content/javascript-parsing-url-parameters

creating DOM nodes from arrays [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Note: This is a continuation of another question that I decided were two separate issues that need to be solved. I'm also currently not sure of how exactly to phrase this question, so I will try my best and when I get more clarity I will rephrase my question for future reference.
I'm writing two basic jQuery plugins, $.fn.query and $.fn.build, that sort an array, and create html code to insert into a document, respectively. I'm currently testing it with Vimeo video ID's that I will display videos with.
$.fn.build has three parts. First it wraps every array item with individual containers, the builds them into rows (problem area), then lastly it wraps everything in a container. (every part of this is optional).
Specifically the problem comes from this line: $(tmp).add(newRow); although it is valid javascript.
if ( options.splitBy !== undefined && options.wrapRow !== undefined ) {
var tmp = $([]),
newRow = function(i) {
$(build.splice( i, i + options.splitBy )).wrapAll( options.wrapRow ).parent();
};
for (var i = 0, l = build.length, a = options.splitBy; i < l; i += a) {
$(tmp).add(newRow);
}
build = tmp;
console.log(build);
}
See: http://jsbin.com/upatus/2/edit
I am quite sure that you want to use the function, instead of adding the function itself. Also, you will want to use the same tmp object all over the time, instead of wrapping it into a new jQuery instance and not adding to the original one. Try
tmp.add(newRow(i));
BTW: If you want to build an array, you should use
var tmp = [];
and
tmp.push(…);
Now I've looked at the code from the other question. Both answers are correct, and contain some valid points:
splice is an Array function on jQuery's prototype, and returns an array. (You have fiexd this now)
Your query method returns an array, but should return a jQuery instance for chaining
Your build variable was not initialized, but used
You should really choose whether you want to use arrays or jQuery objects internally in your function, and not mix them.
BTW, you should rename your functions to more descriptive names. "build" and "query" are very vague and may collide with other plugins.

Categories

Resources