This question already has answers here:
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed 8 years ago.
I am new to json so i am getting a json reponse from my ajax call
now i am stuck with looping the json object
here is my json
{
"0": {
"image": "http://test.com/systems.jpg",
"anchor_tag_link": "http://test.com/1",
"title": "Oct-Dec-2013"
},
"1": {
"image": "http://test.com/energy.jpg",
"anchor_tag_link": "http://test.com/1",
"title": "July-Sept-2013"
},
"pages": 2
}
Can anyone help
You can use a for-in loop as follows:
var obj = {
"0": {
"image": "http://test.com/systems.jpg",
"anchor_tag_link": "http://test.com/1",
"title": "Oct-Dec-2013"
},
"1": {
"image": "http://test.com/energy.jpg",
"anchor_tag_link": "http://test.com/1",
"title": "July-Sept-2013"
},
"pages": 2
}
for(var prop in obj) {
var item = obj[prop];
console.log(item);
}
Be aware that you will get the items in your log because you will get the pages property in addition to the numeric properties.
Save your JSON response in a variable
var variable = {
"0" : {
"image" : "http://test.com/systems.jpg",
"anchor_tag_link" : "http://test.com/1",
"title" : "Oct-Dec-2013"
},
"1" : {
"image" : "http://test.com/energy.jpg",
"anchor_tag_link" : "http://test.com/1",
"title" : "July-Sept-2013"
},
"pages" : 2
};
Then loop it using jquery
$.each(variable, function(index, value) {
alert(value.image);
alert(value.anchor_tag_link);
});
you can do this.
var json = JSON.parse(data);// here data is your response
for (var key in json) {
alert(json[key].image);// other also in the same way.
}
Example 1 :
success: function(responseData) {
for (var key in responseData) {
alert(responseData[key]);
}
}
Example 2 :
<script>
var data = '{"name": "mkyong","age": 30,"address": {"streetAddress": "88 8nd Street","city": "New York"},"phoneNumber": [{"type": "home","number": "111 111-1111"},{"type": "fax","number": "222 222-2222"}]}';
var json = JSON.parse(data);
alert(json["name"]); //mkyong
alert(json.name); //mkyong
alert(json.address.streetAddress); //88 8nd Street
alert(json["address"].city); //New York
alert(json.phoneNumber[0].number); //111 111-1111
alert(json.phoneNumber[1].type); //fax
alert(json.phoneNumber.number); //undefined
</script>
Sample Code
Please try the following code. You only have to replace "yourJSONObject" by the JSON array.
$.each( yourJSONObject, function( keyImg, valImg ) {
image = valImg[0];
anchor_tag_link = valImg[1];
title = valImg[2];
});
Regards,
you can loop through this like looping through javascript object :
for(var arg in object) {
object.hasOwnProperty(arg) {
process(object[arg]);
}
}
JQuery:
var JSON = {
"0": {
"image": "http://test.com/systems.jpg",
"anchor_tag_link": "http://test.com/1",
"title": "Oct-Dec-2013"
},
"1": {
"image": "http://test.com/energy.jpg",
"anchor_tag_link": "http://test.com/1",
"title": "July-Sept-2013"
},
"pages": 2
};
if(JSON.pages >0)
{
for(var i=0; i<JSON.pages; i++)
{
$('table').append('<tr><td>'+JSON[i].title+'</td><td>'+JSON[i].image+'</td><td>'+JSON[i].anchor_tag_link+'</td></tr>');
}
}
HTML:
<table border="1"></table>
Related
This question already has answers here:
Get JavaScript object from array of objects by value of property [duplicate]
(17 answers)
Closed 3 years ago.
I have a JSON file containing 13k objects. I need to get only the objects which have the events { name: "Submitted"} property from it. events is an array of objects which contain multiple name properties. Here is a screenshot of how it looks:
{
"_id": "03c319a5-86d4-4ce6-ba19-1a50584cecb4",
"_rev": "21-7cb67ebb46c485ff443995fc27bdd950",
"doctype": "application",
"events": [{
"name": "change",
"time": 1532547503182
},
{
"name": "change",
"time": 1532547503182
},
{
"name": "submitted",
"time": 1532547503182
},
{
"name": "edited",
"time": 1532547503182
}
]
}
This is how I get all the object inside the json file:
$.getJSON("export.json", function(data) {
var data = [];
var arrays = data;
var i;
for (i = 0; i < arrays.length; i++) {
console.log(arrays[i]);
}
});
Now I need to push all the objects which have events[name:submitted] I get in arrays[i] into the doc[]. How can I filter the results?
You can filter your array of the object by filter method.
$.getJSON("export.json", function(data) {
var data = [];
var arrays = data;
var newArray = arrays.filter(function (el) {
return el.name == 'Submitted';
});
console.log(newArray);
});
You can also do in one line using ES6 arrow function
var newArray = arrays.filter(el => el.name === 'Submitted')
You can use filter(), checking each element in the events array to see if the name is equal to submitted:
const object = {
"_id": "03c319a5-86d4-4ce6-ba19-1a50584cecb4",
"_rev": "21-7cb67ebb46c485ff443995fc27bdd950",
"doctype": "application",
"events": [{
"name": "change",
"time": 1532547503182
},
{
"name": "change",
"time": 1532547503182
},
{
"name": "submitted",
"time": 1532547503182
},
{
"name": "edited",
"time": 1532547503182
}
]
}
const filtered = object.events.filter(obj => obj.name === 'submitted')
console.log(filtered)
My API retrieve a Json like this :
{
"name": "API",
"count": 30,
"newdata": true,
"lastrunstatus": "success",
"thisversionstatus": "success",
"thisversionrun": "Mon Sep 07 2015 20:31:07 GMT+0000 (UTC)",
"results": {
"collection1": [
{
"name": "Item1",
"power": "210",
"name": {
"href": "http://picture.item42.com/item42.html",
"text": "Hammer of god"
},
"desc": "Iron Hammer",
"index": 1,
"url": "http://picture.item42.com/"
},
{
"name": "Item2",
"power": "230",
"name": {
"href": "http://picture.item42.com/item43.html",
"text": "Sword of god"
},
"desc": "Iron sword",
"index": 1,
"url": "http://picture.item43.com/"
}
]
}
I would like to delete the line "url" for each one, and delete le "href" property for the name to have "name" : "Hammer of god";
I try this and many other way (first step to delete the url):
data contains the Json that I copied upper
function transform(data) {
var yourArray = data.results.collection1;
var p = 0;
var i = 0;
var destArr=[];
var srcArr=yourArray;
for(i in srcArr){
if(srcArr[i].url)
destArr[p]=srcArr[i];
p++;
}
srcArr=destArr;
return srcArr;
}
Maybe its better to use data.results.collection1.filter ?
actually my code return the json without the header but still with the url row
Simply go through your json.result.collection1 and remove href on each name and url:
for(item in json.results.collection1) {
delete json.results.collection1[item].name.href
delete json.results.collection1[item].url;
}
Fiddle Example
Use the delete keyword to delete a property from the JSON.
var jsonObj = JSON.parse('your json string');
delete jsobObj.whateveryYourpropertyName;
var json = document.getElementById('json').value;
var obj = JSON.parse(json);
obj.results.collection1.forEach(function(entry) {
delete entry.url;
delete entry.name.href;
});
document.getElementById('result').value = JSON.stringify(obj);
JSFiddle
you should use the JSON delete method for what you want to achieve:
Where data is your json object:
data.results.collection1.forEach(function(el) {
delete el.url
delete el.name.href
});
You can simply use a second forEach loop in case you need to iterate through multiple collections.
Try the following:
jsonData.results.collection1.map(function(obj, index){
delete obj.url;
obj.name = obj.name.text;
return obj;
});
console.log(jsonData);
I have a large JSON file, I am trying to pull out specific key blocks but i am unsure on how to do this.
Current JSON file:
{
"blockID1": {
"name": "name here",
"locale": "en_GB"
},
"blockID2": {
"name": "name here",
"locale": "en_GB"
},
"blockID3": {
"name": "name here",
"locale": "en_GB"
},
"blockID4": {
"name": "name here",
"locale": "en_GB"
}
}
I just want to retrieve blockID3 and blockID4 and then I would output into another json file.
{
"blockID3": {
"name": "name here",
"locale": "en_GB"
},
"blockID4": {
"name": "name here",
"locale": "en_GB"
}
}
Does anyone have an example?
Use an array as a lookup and then loop over the object and if a key is found copy the value to the output object.
var obj = {"blockID1":{"name":"name here","locale":"en_GB"},"blockID2":{"name":"name here","locale":"en_GB"},"blockID3":{"name":"name here","locale":"en_GB"},"blockID4":{"name":"name here","locale":"en_GB"}};
var find = ['blockID3', 'blockID4'];
var out = {};
for (var p in obj) {
if (find.indexOf(p) > -1) {
out[p] = obj[p];
}
}
console.log(out);
Not sure if I understood your question but if you want to output something like that, and you have the ids of the json file if you want you could simply do something like this
const props = ['blockID3', 'blockID4'],
json = {"blockID1":{"name":"name here","locale":"en_GB"},"blockID2":{"name":"name here","locale":"en_GB"},"blockID3":{"name":"name here","locale":"en_GB"},"blockID4":{"name":"name here","locale":"en_GB"}},
res = {};
for(const prop of props) {
if(json[prop]) {
res[prop] = prop;
}
});
At the end res will have the objects that you wanted, hope this helps :)
I have a json data
var data={"mainVariants": [
{
"header": "Measure"
},
{
"header": "Disposal"
},
{
"header": "Stairs"
},
{
"header": "Furniture"
}
],
"Measure": {}}
var val1=data.mainVariants[0].header;//returned as "Measure"
Now i want to retrieve data.val1.Pls help
Try this
var val1 = data.mainVariants[0].getString("header");
You can just do var obj = data[val1]
I have JSON data like this
{
"nodes": [
{
"node": {
"title": "Kieu Oanh",
"Image": "",
"view_node": "view",
"link": "drupal_dev/content/kieu-oanh"
}
},
{
"node": {
"title": "Kieu Oanh",
"Image": "",
"view_node": "view",
"link": "drupal_dev/content/kieu-oanh"
}
},
]
}
Now I want to convert it to
var rel_data = [{
"title": "asa",
"Image": "sasa",
"view_node": "sajsjla"
}, {
"title": "asa",
"Image": "sasa",
"view_node": "sajsjla"
}]
And This is my code to convert data to rel_data
data = data.nodes;
for (d in data) {
rel_data[d].title = data[d].node.title;
rel_data[d].image = data[d].node.Image;
}
for (d in rel_data) {
alert(rel_data[d].title);
}
But it does not seem to work, is there anything wrong in my code?
You're trying to edit objects which aren't there yet.
The first thing you do is access rel_data while there is no rel_data yet. The second thing you do is that you change properties of array elements which do not exist.
Your code should be the following to work:
data = data.nodes;
rel_data = new Array(); // Create rel_data
for(d in data) {
rel_data[d] = new Object(); // Create array element
rel_data[d].title= data[d].node.title;
rel_data[d].image= data[d].node.Image;
}
for(d in rel_data) {
alert(rel_data[d].title);
}
You could also use map instead of a for loop (for generating the new array, you'd want one for the alert())
var rel_Data = data.nodes.map(function(item) {
return {
"title": item.node.title,
"Image": item.node.Image,
"view_node": item.node.view_node
};
});