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.
Related
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');
I want to fetch only 1st element of json array
my json data :
{
id:"1",
price:"130000.0",
user:55,
}
{
id:"2",
price:"140000.0",
user:55,
}
i want to access the price of 1st json element
price : "13000.0"
my code
$.each(data_obj, function(index, element) {
$('#price').append(element.price[0]);
});
but my output
is '1'
Assuming that you have array of objects
var arr = [{
id:"1",
price:"130000.0",
user:55,
},
{
id:"2",
price:"140000.0",
user:55,
}]
console.log(arr[0].price)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You data isn't valid JSON, JSON data key must be wrap within double quote, but your data isn't wrapped in double quote
var data = [{
"id":"1",
"price":"130000.0",
"user":55
},{
"id":"2",
"price":"140000.0",
"user":55
}]
console.log(data[0]["price"]);
Hello You just need to add [] from starting and ending point of your json string. see here var data = JSON.parse( '[{ "id":"1","price":"130000.0","user":55},{"id":"2","price":"140000.0","user":55}]');
var priceValue = 0;
$.each(data, function(index, element) {if(index == 0){ priceValue = element.price;}});console.log(priceValue);
Your answer will be 13000.0
The element having the your JSON data means, we can able to use below code to get the first JSON data.
element[0].price
Thanks,
You are using for each loop and in function you get 2 params first one is index and second is the element itself. So this will iterate through all elements.
$.each(data_obj, function(index, element) {
$('#price').append(element.price);
});
If you just want to get first element
$('#price').append(data_obj[0].price);
var my_first_json_obj = data_obj[0]; // Your first JSON obj (if it's an array of json object)
var my_price = my_first_json_obj.price; // Your price
$('#price').append(my_price);
If you want only the first item's price, you don't need a loop here.
$('#price').append(data_obj[0].price);
would work here.
For further reading you can refer here
Following is the solution worked for my problem
I use return false;
$.each(data_obj, function(index, element) {
$('#price').append(element.price[0]);
return false;
});
Which gives only 1st value of array elements.
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
I'm struggling with a issue populating a DropDown menu with an array.
My array, stored in an external json files is in the following format :
[{"name":"value_A", "other":"value_A1"}, {"name":"value_B1"}, {"name":"value_C"} ]
In order to use these data, I first push them in a array, then try to push them in a drop down menu.
My jQuery looks like the foolwoing :
function loadData() {
$.getJSON(database, function (data) {
for(var i=0; i<data.length; i++) {
myNewArray.push(
{
"name":data[i].name
})
$.each(data, function(i, item) {
$("#myDiv").append('<option>' + data[i].name + '</option>')
});
};
});
}
It works "well" as dat go to my drop down menu, but it iterate all the data as the same amount of object.
For example, I f I got 10 objets in my array, it return 10 times the whole values asked
How to "stop" the iteration after query deliver the selected
[{"name":"value_A", "other":"value_A1"}, {"name":"value_B"}, {"name":"value_C"} ]
will return in a console :
value_A
value_B
value_C
value_A
value_B
value_C
value_A
value_B
value_C
I think I'm not so far for the good code, but after testing lot of combination, I can't solve it withou your help.
Thanks for any advise on this.
You have a $.each() inside a for loop, so it creates a double iteration causing same elements to be added multiple times.
Only one of $.each() or the for loop is required
function loadData() {
$.getJSON(database, function (data) {
$.each(data, function (i, item) {
myNewArray.push({
"name": item.name
})
$("#myDiv").append('<option>' + item.name + '</option>')
});
});
}
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 );
});
});