How to create dynamic variables in Angularjs, javascript and other scripting language? - javascript

I want to create dynamic variables like Vikas0, Vikas1, Vikas2, Vikas3 and so on.
$.each(data, function(key, value){
$scope.servicesDataList[key].list="Vikas"+key;
// will print Vikas0, Vikas1, Vikas2, Vikas3
console.log($scope.servicesDataList[key].list);
});
Now I want to create dynamic variables. Will any one knows how can I achieve this. I hope I am able to elaborate my question.

You can use.
the syntax would be = $scope["vikas"+key] = []
$.each(data, function(key, value){
$scope["Vikas"+key] = value;
console.log($scope["vikas"+key].value);
will print Vikas0, Vikas1,Vikas2, Vikas3
});

You can with using array of object act as a dynamic variable.
Var conctVar="":
$.each(data, function(key, value){
conctVar= conctVar + "{Vikas"+key + ":Vikas"+value+"},";
});
conctVar=conctVar.slice(0,-1);
$scope.FinalObject=JSON.parse(conctVar);// now the string will convert to a array object
Now you can get the array object looks like below
$scope.FinalObject.Vikas1,// value is vikas1
$scope.FinalObject.Vikas2,// value is vikas2
$scope.FinalObject.Vikas3,//value is vikas3
$scope.FinalObject.Vikas4//value is vikas4

Related

jquery each for json

I get JSON from my endpoint:
[{"phone":71111111111,"debt":1},{"phone":72222222222,"debt":2},{"phone":73333333333,"debt":3}]
after it, i use:
data = jQuery.parseJSON(data);
how i can show data from json with jquery each?
i try to do this but it not works correctly:
$.each(data, function (key, data2) {
$.each(data2, function (index, value) {
console.log(value['phone']);
});
for ex, it must show (with jquery) only phones, like:
71111111111
72222222222
73333333333
but show me "undefined"
Remove the inner loop.
The outer one already provide you the expected object, such as {"phone":71111111111,"debt":1}
The inner one will enumerate the values of those objects 71111111111 and 1 in the above example.
(71111111111)['phone'] is undefined, because there are no property phone in the number 71111111111
const json = '[{"phone":71111111111,"debt":1},{"phone":72222222222,"debt":2},{"phone":73333333333,"debt":3}]';
const data = jQuery.parseJSON(json);
$.each(data, function (key, data2) {
console.log(data2['phone']);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You only need to use jQuery.each once to loop over the array of objects. It is crucial to note that the first argument given to the callback is the index and the second one is the actual element.
var data = [{"phone":71111111111,"debt":1},{"phone":72222222222,"debt":2},{"phone":73333333333,"debt":3}];
$.each(data, function (idx, obj) {
console.log(obj.phone);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Why don't you use the Vanilla forEach method? You can do your job like-
data.forEach(({phone, debt}) => {
console.log(phone);
});
It's easy and pure, isn't it?
There is no need to do a $.each again. data2 is the object in which phone is contained, so all you have to do is this:
$.each(data, function(key, data2){
console.log(data2['phone']);
}
This yeilds the correct output.
I also want to note that you do not have to use $.each() in order to loop through an array. Instead, you can use foreach.

What is the correct way to handle this data using jQuery?

I have a list of html elements with data attributes, which I would like to assemble into a jQuery object and manipulate the values.
What is the best way to dynamically add these in an each loop so that I can easily access the data as so: data.name and data.name.prop?
I want all the naming conventions to be dynamic and based on the data.
I based my code on the top answer from here: How to create dynamically named JavaScript object properties?
So far I have:
$('.licences-list .data div').each(function(index) {
var data = {}
cats[$(this).find('p').data('cat')] = $(this).find('p').data('catname')
cats.push(data)
})
But when I try to iterate over the data array, like so:
$.each(cats, function(key, value){
$('<div class="card"><p>'+value+'</p></div>').appendTo('#commercial-licenses');
});
I just get [object Object] output... and I'm not sure why!
var data = {}
cats[$(this).find('p').data('cat')] = $(this).find('p').data('catname')
Each time you loop through, you're actually just adding an empty object (data) to your array (cats). You're then assigning a named property to that array (cats) which $.each has no idea about (it ignores them because it's iterating over an actual array).
My guess is you want an object map which is something like: var cats = { "f1": "feline 1", "f2": "feline " };
In that case what you want is:
var cats = {};
$('.licences-list .data div').each(function(index) {
cats[$(this).find('p').data('cat')] = $(this).find('p').data('catname')
})
If you want an array that contain more values than just strings (or whatever data you have added to the element), you create new objects each time and append them to the cats array:
var cats = [];
$('.licences-list .data div').each(function(index) {
cats.push({
'id': $(this).find('p').data('cat'),
'name': $(this).find('p').data('catname')
});
})
This will then give you an array that you can use $.each over, and access the values using: value.id, value.name
Don't over complicate it.
$('.div').attr('data-attribute', 'data-value');
using your example:
$('.licences-list .data div').attr('attribute-name', 'attribute-value');

Accessing a value in JSON

I am trying to access the country names from this json -
https://restcountries.eu/rest/v1/all
This is my code for loading that json -
<script>
(function() {
var country = "https://restcountries.eu/rest/v1/all";
$.getJSON( country)
.done(function( data ) {
$.each(data, function(key, value) {
$('#mySelect').empty();
$('#myselect').append('<option>' + data.name + '</option>');
});
});
})();
</script>
The problem may be in data.name statement. I couldn't find any solution on my own. Plus, i am new to JSON. Any help or at least any comment to point my faults will be appreciated.
it should be value.name, data is the array you get from the api, value is each item in the array. also, remove empty as it's remove everything in each loop cyle...
see working code here

javascript/jquery indicate something is a variable

I have a function that injects user's data into html file
the json format is something like this:
{"Fname":"abc","LName":"cdf", "Phone":"123456";}
this is a function to inject data into html file:
function injectData(data){
$.each(data, function(key, value) {
//notice that in the "data.value", I want 'value' to be a variable
//so that when I loop over the array, data.value will become data.Fname,
//and then data.LName and then data.Phone
$("#"+key).html(' ' + data.value +'');
});
How can I force javascript to interpret 'value' as a variable first before calling data.value in order to get the real value from JSON object? This is a little bit confusing. Hope you understand .Thank you
Write something like:
for(key in data){ $("#"+key).html(' ' + data[key] +''); });

how to browse a javascript object

I'm new to jQuery. Following is the data variable that contains a json dictionary.
{
"user":null,
"currency":"EUR",
"balance":0,
"translist": [
{ "trans1":"something","trans2":"something2" }
]
}
and my jQuery method receives a json/Javascript object from the Rest GET call
success: function (data){
for(x in data) {
console.log(x + ': ' + data[x]);
}
});
Is there any library that can help to parse/walk through this json object and get to some kind of objects list? I want to check some of the keys and their respective values. Problem is I don't need all the keys and values from the list and also some of the values can be null, which prevented me to apply some solutions I found using SO.
Or usually is it more common to directly start printing the HTML inside the success function?
EDIT:If it was java for example it would be a Map and I would use an iterator to walk through and see/analyse the map values, and create some array list with the values I want from it. What's equivalent of that in jQuery?
If it was java for example it would be a Map and I would use an
iterator to walk through and see/analyse the map values, and create
some arraylist with the values I want in it. What is the equivalent of that
in jQuery?
Any javascript object can be seen as an associative map.
You can for example directly access the currency as data['currency'].
You can also build an array :
var a = [];
for (var key in data) {
a.push({key:key, value:data[key]});
}
You could also build some HTML and apply functions to the data :
$(document.body).append($(
'<table>' + a.map(function(v){
return '<tr><td>'+v.key+'</td><td>'+v.value+'</td></tr>'
}).join('')+'</table>'
));
Demonstration
Using jQuery can make the same iteration simpler (working directly from data) :
$(document.body).append($(
'<table>' + $.map(data, function(value,key){
return '<tr><td>'+key+'</td><td>'+value+'</td></tr>'
}).join('')+'</table>'
));
Demonstration
Try using each
success: function (data){
$.each( data, function( key, value ) {
if(key === "currency")
alert( key + ": " + value );
});
});

Categories

Resources