JavaScript for(-each) loop [duplicate] - javascript

This question already has answers here:
How do I enumerate the properties of a JavaScript object? [duplicate]
(14 answers)
Closed 6 years ago.
I have a JSON-Array and want to loop though it. I know that there is no foreach-loop (like in PHP), but is there a possibility to access the field index of the array?
This is my json:
{
'username': 'Karl',
'email': 'xyz#abc.xx',
'user_id': 5,
...
}
I have some span elements on my page with a data-field attribute. E.g:
<span data-field="username">xyz</span>
The json-array is the return of an ajax-request. With it, I want to replace every element where the data-field="" matches the array-index.
Right know, I do it this way for each element in the json-array:
$("[data-field='username']").text(data.username);
$("[data-field='email']").text(data.email);
But with more and more elements this becomes a little bit ugly^^
Any other possibilties? I read something about transforming the json to an object, but I have no idea how to do.

The for each loop in javascript would look like below.
for(var key in Json){
$("[data-field='"+ key +"']").text(Json[key]);
}

Related

How to easily print nested objects without naming each one [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed 1 year ago.
I have an object of objects in which I want to print all the name values, how can I do this easily without having to hardcode each one?
const myObj = {
results: {
one: {
name: "o",
value: 1
}
two: {
name: "t",
value: 2
}
}
ignore: "this"
}
I can make it work with myObj.results.one.name, but I'd rather be able to do something like a loop where I can swap out the middle value like results.[1].name preventing the hard coding of 20 values.
Is there a simple way to do this without hardcoding each one. (The end use is to add them all to an array and use that to populate a table to show name and values)
This linked answer doesn't answer my question as this is an array of objects so solutions fail, and the second isn't nested

How to use custom variable in JavaScript [duplicate]

This question already has answers here:
Javascript getElementById based on a partial string
(9 answers)
Closed 3 years ago.
I just want to know to how to use custom varible with javascript.suppose we have 5 id with name zawsz,baws2,tawsx,paws4,vawsa and we want to execute single DOM command to all these element whose id is define here.
document.getElementById("-aws-").onclick=function(){}
Here -aws- define all the id define above.(-) can be replace with any char/int value;
You could use the following code:
(The following code will select all elements of which the id includes aws.
I have tested this code and it works: https://jsfiddle.net/5042woqz/)
document.querySelectorAll('*[id*="aws"]').forEach(function(item) {
item.onclick=function() {
console.log('click!');
};
});
Items will now be an array containing all your aws- items.
If you have further questions, just let me know.
P.S.: You could achieve the same thing really easily with jquery.
You can use document.querySelectorAll for this:
document.querySelectorAll('[id^="aws"]')
That will select all elements where the id attribute starts with (^=) "aws".

Retrieving parameter from query string based on another string in Javascript [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 4 years ago.
My app in Google Apps Script gets data from a form that I want to process.
The element form is received and contains the different parameters and values.
If I log the element form it looks like {uid=11, tradingname=xxx, email=yyy}
I can pick up the separate values by running form.uid or form.tradingname for example. But what I want is to pick up the parameters from the element form by referring to a String "uid" (because I get this value form the headers row of the spreadsheet).
Is there a simple way I can do this in one line, for example something like:
form.element["uid"]
So far I've only found difficult methods like https://gomakethings.com/how-to-get-the-value-of-a-querystring-with-native-javascript/ and I would think that I should be able to do this in an easier way.
Thanks!
You can use $("#yourform").serializeArray() and then iterate to match "name" values you want

How do I use a variable to find an element in an array? [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 6 years ago.
I'd like to take some user input and use it to find a certain object in an array. But when I try to do it with the code below, I get an undefined error. What am I doing wrong?
function findNextLevel() {
var currentLevel = parseFloat(document.getElementById("currentLevel").value);
var xpForLevel = trainerLevels.currentLevel;
document.getElementById("result01").innerHTML = xpForLevel;
}
I'm assuming that trainerLevels is an array and currentLevel is an index. If so, the way to access an element in an array at a certain index is to use brackets like so. Otherwise, could you provide more details in your question?
var xpForLevel = trainerLevels[currentLevel];
If this is the answer that you were looking for, then may I recommend that you use the parseInt rather than the parseFloat function for getting the index? And also, since it is user input, you may want to check that currentLevel is in the correct range as well.

How to access this attribute [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
I'm new to JavaScript and I've been stuck on this for a little while now. Let's say I have an object inside an array inside an object, like so:
var myCrazyObject = { "name": "A ridiculous object", "some array": [7, 9, { purpose: "confusion", number: 123 }, 3.3], "random animal": "Banana Shark"};
Now I know that I can access the "some array" attribute thusly:
myCrazyObject["some array"]
So, the part that I'm stuck on is, how do I access the purpose or number attributes?
It is the third element in your array, so you can access it by index:
myCrazyObject["some array"][2].purpose
or if you prefer the equivalent:
myCrazyObject["some array"][2]["purpose"]
would return "confusion". Obviously it's pretty brittle stuff. Normally you should be storing elements of the same type inside an array and not some integers at the beginning and then another arbitrary object. If for some reason the third element in this array wasn't an object you would get an error. So it's up to you to make the proper error handling here or fix your data input in order to bring some consistency here.

Categories

Resources