The jQuery below illustrates how I get the products from https://dummyjson.com/products. However, I don't know how to iterate the loop to retrieve each of the 30 products in the link and the details of each product.
$.get("https://dummyjson.com/products/1")
.done(function(data, textStatus, jqXHR){
console.log("typeof(data) is: " + typeof(data));
console.log("data is: "+ data);
console.log(data.length);
var result = [];
result = JSON.parse(JSON.stringify(data));
console.log(typeof(result));
console.log(result.length);
var keys = Object.keys(result);
keys.forEach(function (key) {
console.log("forEach");
console.log(key, result[key]);
//console.log(result[0]);
});
})
.fail(function(jqXHR, textStatus, errorThrown){
alert("error");
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
});
You should iterate through the object itself instead of the keys. Also, use let instead of var (see here).
$.get("https://dummyjson.com/products/1")
.done(function(data) {
let result = JSON.parse(JSON.stringify(data));
$.each( result, function( key, value ) {
console.log( key + ": " + value );
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
For multiple products you need another for loop to iterate through each product:
$(document).ready(function() {
$.get("https://dummyjson.com/products")
.done(function(data) {
let result = JSON.parse(JSON.stringify(data));
$.each(result, function( key, products) {
for (let i = 0; i < products.length; ++i) {
console.log(products[i].id);
console.log(products[i].title);
console.log(products[i].description);
}
});
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Thats is totally depends upon how was your reponse are.
If your response like this.
{
"status": true,
"data" : [
{
"id": 1,
"name": "xyz",
},
{
"id": 2,
"name": "xyz",
}
]
}
then you have to use following code:
$.get('/your-url', function(response) {
if(response.status) {
$.each(response.data, function(index, item) {
console.log(item);
})
} else {
alert('Your API sent false status')
}
})
Otherwise your response something like this.
[
{
"id": 1,
"name": "xyz",
},
{
"id": 2,
"name": "xyz",
}
]
then you have to use following code:
$.get('/your-url', function(response) {
$.each(response, function(index, item) {
console.log(item);
})
})
Related
I have to write map function based on response data but response data is not an array
example response
{
"data": {
"e680c823-895b-46f0-b0a0-5f8c7ce57cb2": {
"id": 98218,
......
},
"e24ed385-0b86-422e-a4cc-69064846e13b": {
"id": 98217,
.......
},
"c1cc583b-a2be-412b-a286-436563984685": {
"id": 118868,
.....
},
}
var posts = data.map(function (item) {
return item.id;
});
I have to achieve like this console
console.log( posts[1].id ) //98217
map over the Object.values and return the nested object.
const data = {
data: {
"e680c823-895b-46f0-b0a0-5f8c7ce57cb2": {
"id": 98218
},
"e24ed385-0b86-422e-a4cc-69064846e13b": {
"id": 98217
},
"c1cc583b-a2be-412b-a286-436563984685": {
"id": 118868
}
}
};
const posts = Object.values(data.data).map(obj => obj);
console.log(posts[1].id);
Object.values() returns an array of Object values. You can loop over them to get your desired result.
let respData = {
"data": {
"e680c823-895b-46f0-b0a0-5f8c7ce57cb2": {
"id": 98218
},
"e24ed385-0b86-422e-a4cc-69064846e13b": {
"id": 98217
},
"c1cc583b-a2be-412b-a286-436563984685": {
"id": 118868
}
}
}
var posts = Object.values(respData['data']).map(function (item) {
return item;
});
console.log(posts[0].id) //98218
I need help replacing data inside of a JSON file using NODE.JS. My current method adds it with the same ID which is correct. However, when the data is received back, it drops the last duplicate because it found the old value first. I think what I really need to do is select JSON element by ID. Then replace it with the new.
Here is my AJAX request:
putComment: function(commentJSON, success, error) {
$.ajax({
type: 'post',
url: 'http://localhost:8080',
data: JSON.stringify(commentJSON),
success: function(comment) {
success(comment)
},
error: error
});
},
Here's my NODE:
if (req.method == 'POST') {
req.on('data', function(chunk) {
var element = JSON.parse(chunk);
fs.readFile("comments-data.json", 'utf8', function(err, json) {
var array = JSON.parse(json);
array.push(element);
fs.writeFile("comments-data.json", JSON.stringify(array), function(err) {
if (err) {
console.log(err);
return;
}
console.log("The file was saved!");
});
});
res.end('{"msg": "success"}');
});
};
Here is the data with duplicate id's:
[
{
"id": "c1",
"parent": null,
"created": "2016-08-12T19:57:21.282Z",
"modified": "2016-08-12T19:57:21.282Z",
"content": "test",
"fullname": "John Clark",
"profile_picture_url": "https://viima-app.s3.amazonaws.com/media/user_profiles/user-icon.png",
"created_by_current_user": true,
"upvote_count": 0,
"user_has_upvoted": false
},
{
"id": "c1",
"parent": null,
"created": "2016-08-12T19:57:21.282Z",
"modified": 1471031853696,
"content": "test 123",
"fullname": "John Clark",
"profile_picture_url": "https://viima-app.s3.amazonaws.com/media/user_profiles/user-icon.png",
"created_by_current_user": true,
"upvote_count": 0,
"user_has_upvoted": false
}
]
Are you just trying to replace the item if it exists? If so, you could do something like this:
var array = JSON.parse(json);
var isNew = true;
for (var i = 0; i < array.length; i++) {
if (array[i].id === element.id) {
array[i] = element;
isNew = false;
break;
}
}
//doesn't exist yet
if (isNew) {
array.push(element);
}
fs.writeFile("comments-data.json", JSON.stringify(array), function(err) {
if (err) {
console.log(err);
return;
}
console.log("The file was saved!");
});
My JSON file:
[{"val0":"Paul","val1":"Jake","val2":null,"val3":"Max"},
{"val0":"Sam","val1":"Tina","val2":"Emily","val3":"Hardwell"},
{"val0":"Tom","val1":"Julie","val2":null,"val3":"Adi"}]
I want to create an array in javascript as follows:
var dataSet=[
['Paul','Jake','null','Max'],
['Sam','Tina','Emily','Harwell'],
['Tom','Julie','null','Adi']
];
I tried the following code but it isn’t working. Can anybody please help?
$.getJSON("filename.json", function(data) {
var items = [];
$.each(data, function(key, val) {
items.push(val);
});
// …
});
I’m using this array for display purpose (using DataTables), so, I want to create the array in that format.I'm using the dataSet array for displaying in DataTables as follows:
var dataSet = [
['Paul','Jake','Isha','Mike','null','null','Parth','Tinker'],
['Tina','Michael','null','Blue','Red','','Emily','Mina']
];
$(document).ready(function() {
$('#demo').html( '<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"></table>' );
$('#example').dataTable( {
"data": dataSet,
"columns": [
{ "title": "Name" },
{ "title": "Deadline" },
{ "title": "Additional fees" },
{ "title": "Requirements" },
{ "title": "Field" },
{ "title": "Award" },
{ "title": "Renewable requirements"},
{ "title": "Link" }
]
} );
} );
You get an array of objects, and you want an array of arrays, so convert each object to an array by reading the properties of the object:
var items = [];
$.each( data, function( key, val ) {
items.push([val.val0,val.val1,val.val2,val.val3]);
});
Try this
<script>
$(function() {
$.getJSON("filename.json", function(data) {
var items = [];
$.each(data, function(key, val) {
var tmp = [];
for (var Key in val) {
tmp.push(val[Key]);
}
items.push(tmp);
});
console.log(items);
});
});
A solution without jquery:
var data = [
{ "val0": "Paul", "val1": "Jake", "val2": null, "val3": "Max" },
{ "val0": "Sam", "val1": "Tina", "val2": "Emily", "val3": "Hardwell" },
{ "val0": "Tom", "val1": "Julie", "val2": null, "val3": "Adi" }
],
dataSet = data.reduce(function (r, a) {
var i, a0 = [];
for (i in a) {
a0.push(a[i]);
}
r.push(a0);
return r;
}, []);
document.getElementById('out').innerHTML = JSON.stringify(dataSet, null, 4);
<pre id="out"></pre>
One liner:
var dataSet = rawData.map(function(e){ return Object.keys(e).map(function(i){ return e[i]}); })
Output:
Output as JSON:
Method explanation (from Javascript Reference)
The map() method creates a new array with the results of calling a provided function on every element in this array.
The Object.keys() method returns an array of a given object's own enumerable properties
Please take a look at this fiddle
How can I use slice in the loop to make it return results starting from a specific index?
The JSON file:
[
{
"title": "A",
"link": "google.com",
"image": "image.com",
"price": "$1295.00",
"brand": "ABC",
"color": "Black",
"material": "Rubber"
}
]
I want it to return results starting from brand:
brand - ABC
color - Black
material - Rubber
I don't know where to put .slice(4) in the loop. I got undefined error using
$.each(value.slice(4),function(key, value)
Here's the code:
JS:
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%22http%3A%2F%2Fgoo.gl%2FaZgYDB%22&format=json&diagnostics=true&callback=",
success: function (data) {
var item_html="";
$(data.query.results.json).each(function(key, value) {
$.each(value,function(key, value){
item_html += '<h3>'+key+' - '+value+'</h3>';
});
});
$('#area').append(item_html);
}
});
Use a separate array of property names, so you can slice it and get the names in a guaranteed order.
var props = [
"title",
"link",
"image",
"price",
"brand",
"color",
"material"
];
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%22http%3A%2F%2Fgoo.gl%2FaZgYDB%22&format=json&diagnostics=true&callback=",
dataType: 'json',
success: function (data) {
var item_html="";
var propslice = props.slice(4);
$.each(data.query.results.json, function(i, obj) {
$.each(propslice, function(i, key) {
value = obj[key];
item_html += '<h3>'+key+' - '+value+'</h3>';
});
});
$('#area').append(item_html);
}
});
If there are a small number of properties you want to skip, you can make a list of them in an object, and test against that list:
var excluded_props = {
title: true,
link: true,
image: true,
price: true
};
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%22http%3A%2F%2Fgoo.gl%2FaZgYDB%22&format=json&diagnostics=true&callback=",
dataType: 'json',
success: function (data) {
var item_html="";
$.each(data.query.results.json, function(i, obj) {
$.each(obj, function(key, value) {
if (!excluded_props[key]) {
value = obj[key];
item_html += '<h3>'+key+' - '+value+'</h3>';
}
});
});
$('#area').append(item_html);
}
});
What you're asking for isn't possible with an object. Objects in Javascript are not ordered, only arrays. You have a few options:
Refactor your object to be an array
Refactor your object so that each key has a new key for order*
loop through each property of the object, placing it into an array (no guaranteed order!) and then looping through the array.
*Example:
[
{
"title": {
"value" : "A",
"order" : 4
},
"link": {
"value" : "google.com",
"order" : 5
...
}
]
[
[
{
"Id": 3,
"Code": "232",
"TicketImage": "0"
}
],
[
{
"Id": 1,
"Code": "23",
"TicketImage": "1"
},
{
"Id": 2,
"Code": "24",
"TicketImage": "1"
}
],
[]
]
I have this JSon object which I m trying to parse.
var res = jQuery.parseJSON(JSON.stringify(obj.Message));
$.each(res, function (i, tickets) {
$.each(tickets, function (i, ticket) {
console.log($(this));
});
});
When i try this i get zillions of popups with letters. but i want object.
How can i parse this JSON data?
UPDATE:
$.each(res, function (i, tickets) {
$.each(tickets, function (i, ticket) {
console.log(ticket.Code);
console.log(ticket.TicketImage);
});
});
This did it.
Careful you are overriding the i variable :
$.each(res, function (i, tickets) {
$.each(tickets, function (j, ticket) {
console.log(this);
// as a full string
console.log(this.ticketId+' : '+JSON.stringify(this));
});
});
Besides this small thing, your loop is correct, you don't need the jquery wrapper on your 'this'. in $.each(array,function(k,v){}) , the k variable is the key to retrieve the current object and v it's value so you could also access it by doing this :
$.each(res, function (i, tickets) {
$.each(res[i], function (j, ticket) {
console.log(res[i][j].ticketId+' : '+res[i][j]);
// which is the exact same thing as :
console.log.(ticket);
// and even this:
console.(this);
});
});
The same code using 'this' :
$.each(res, function (i, tickets) {
$.each(this, function (j, ticket) {
console.log(this.ticketId+' : '+this);
});
});
using each value :
$.each(res, function (i, tickets) {
$.each(tickets, function (j, ticket) {
console.log(ticket.ticketId+' : '+ticket);
});
});
Try:
var res = jQuery.parseJSON(eval(obj.Message));