I am trying to parse the following JSON with jQuery and get each id value. Can anyone advise?
[
{
"id": "1",
"name": "Boat"
},
{
"id": "2",
"name": "Cable"
}
]
So far I have:
$.each(test, function(i,item){
alert(item);
});
But that simply lists every value. How can I
That'll list every object in your array, to get the id property of the one you're on, just add .id like this:
$.each(test, function(i,item){
alert(item.id);
});
If test is a string containing JSON, you can parse it with jQuery.parseJSON, which will return a JavaScript object.
If test is written like this:
var test = [
{
"id": "1",
"name": "Boat"
},
{
"id": "2",
"name": "Cable"
}
];
...it already is a JavaScript object; specifically an array. jQuery.each will loop through each array entry. If you want to loop through the properties of those entries as well, you can use a second loop:
$.each(test, function(outerKey, outerValue) {
// At this level, outerKey is the key (index, mostly) in the
// outer array, so 0 or 1 in your case. outerValue is the
// object assigned to that array entry.
$.each(outerValue, function(innerKey, innerValue) {
// At this level, innerKey is the property name in the object,
// and innerValue is the property's value
});
});
Live example
Related
Is there any way to compare two arrays and push to an empty array if the condition is met?
Say I have an array of objects. I need to loop through the array of objects, get a ID; then compare that ID to a different array. Then if they match push a value in that array to an empty array?
Array 1:
[{
"addon_service": {
"id": "f6f28cb5-78ad-4ec7-896d-16462b8202fd",
"name": "papertrail"
},
"app": {
"id": "199a1f26-b8e2-43f6-9bab-6e7a6c685ec2",
"name": "mdda-mobiledocdelivery-stg"
}
}]
Array 2
[{
"app": {
"id": "199a1f26-b8e2-43f6-9bab-6e7a6c685ec2"
},
"stage": "staging",
}]
I need to match Array 1 app.ID to Array 2 app.id. If they match check what stage the app is in (staging, development or production). Then push Array 1 addon_service.name to either a staging develpment or
production array depending on what stage the application is in. I'm thinking its simple just cant get my head around it.
I think this is a poorly worded question.
You could use a hash table for lookup and for the stage and use an object for collecting the matches.
var array1 = [{ "addon_service": { "id": "f6f28cb5-78ad-4ec7-896d-16462b8202fd", "name": "papertrail" }, "app": { "id": "199a1f26-b8e2-43f6-9bab-6e7a6c685ec2", "name": "mdda-mobiledocdelivery-stg" } }],
array2 = [{ "app": { "id": "199a1f26-b8e2-43f6-9bab-6e7a6c685ec2" }, "stage": "staging", }],
hash = Object.create(null),
result = {};
array2.forEach(function (a) {
hash[a.app.id] = a.stage;
});
array1.forEach(function (a) {
if (hash[a.app.id]) {
result[hash[a.app.id]] = result[hash[a.app.id]] || [];
result[hash[a.app.id]].push(a.addon_service.name);
}
})
console.log(result);
I think this will do it.
$.each(app1, function(key, value){
$.each(app2, function(k, v){
if(value.app.id == v.app.id){// find apps with the same `id`
if(v[v.stage]){// check if the `stage` array already exists.
v[v.stage].push(value.addon_service)
}else{
v[v.stage] = [value.addon_service];
}
}
});
});
Where app1 is the first array in your question and app2 the second one.
I'm new to jQuery, and I'm trying out the getJSON function. What I want to do is pull the "id" section of a JSON file and push it into an array called planes in jQuery. From there, the array is used in an autocomplete function to fill in the searchable IDs.
var planes = [];
$.getJSON('planes.json', function(data) {
console.log('Filling array...');
//This is where I think the issue is occurring.
//Is using the name of the section you want to use the correct syntax here?
$.each(data.id, function (index, val) {
planes.push(val.id);
console.log('Pushed ' + index);
});
});
// After getJSON, array should look something like this:
// var planes = [
// 'Alara',
// 'Fiora',
// 'Innistrad',
// 'Kamigawa',
// 'Lorwyn',
// 'Mirrodin',
// 'Ravnica',
// 'Shandalar',
// 'Zendikar'
// ];
The JSON file is arranged like so:
[
{"id": "Ravnica"},
{"id": "Lorwyn"},
{"id": "Innistrad"},
{"id": "Zendikar"},
{"id": "Kamigawa"},
{"id": "Mirrodin"},
{"id": "Shandalar"},
{"id": "Alara"},
{"id": "Fiora"}
]
Plunker
Any help is much appreciated.
You almost have it, although you are looping through data.id which is not what you want to be doing. You should just loop through data, and push val.id.
If you wanted to loop through data.id, then you're json would have to be structured like so:
{
"id": [
"things",
"to",
"loop",
"through"
]
}
..but it's not, so just loop through data.
Please check following solution. I have hard coded plane data instead of getting from file but solution is same. You just need update your $.each line by iterating over data instead of data.id (this is you'r bug rest of code is fine).
var data = [{
"id": "Ravnica"
}, {
"id": "Lorwyn"
}, {
"id": "Innistrad"
}, {
"id": "Zendikar"
}, {
"id": "Kamigawa"
}, {
"id": "Mirrodin"
}, {
"id": "Shandalar"
}, {
"id": "Alara"
}, {
"id": "Fiora"
}];
var planes = [];
//surround this each with your $.getJSON. I have just hardcoded json data instead of getting it from file
$.each(data, function(index, val) {
planes.push(val.id);
});
console.log(planes);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Your update plunker link Plunker
You might also look into the native array map method, which saves you having to create an array and then push things onto it. It just returns a new array given the original array by applying the mapping function on each item.
$.getJSON("planes.json",function(data){
console.log(data.map(function(plane){return plane.id;}))
}
However, this is not available in IE<=8 if I recall correctly.
I am working Angular js project, I am getting form server response is JSON Object. That JSON Object contains nested Objects and Arrays. for every time i need write lot coding getting the value of key
Ex:
{
"mapData": {
"data": [
{
"key": "name",
"value": "abc"
},
{
"key": "name",
"value": "bcd"
},
{
"key": "name",
"value": "vbc"
}
]
}
}
what i was tried example is so many times, it is not related above example.
for(var key in object) {
if(key=="Id"){
Id= object[key].fieldValue;
secondData.forEach(function(item){
for(var innerItem in item){
if(innerItem =="Id"){
if(Id==item[innerItem].fieldValue){
FinalData.push(item);
}
}
}
});
}
}
Is there any way generic way Instead of writing every time for for loop and For Each loop.
could you please suggest any things
Thanks in advance
mapData.data[i].key will return your key value. i is index of your data array you can easily iterate data by
for(var i =0;i<mapData.data.length;i++){}
If I have a JSON Object Map :
var dataItem=[{
"Lucy":{
"id": 456,
"full_name": "GOOBER, ANGELA",
"user_id": "2733245678",
"stin": "2733212346"
},
"Myra":{
"id": 123,
"full_name": "BOB, STEVE",
"user_id": "abc213",
"stin": "9040923411"
}
}]
I want to iterate through this list and access the names (i.e. Lucy, Myra ) and corresponding information
All the loops that I came across looped through the list like this :
var dataItem = [
{"Name":"Nthal","Class":3,"SubjectName":"English "},
{"Name":"Mishal","Class":4,"SubjectName":"Grammer"},
{"Name":"Sanjeev","Class":3,"SubjectName":"Social"},
{"Name":"Michal","Class":5,"SubjectName":"Gk"},
]
for(x in dataItem)
{
alert(dataItem[x].Name);
alert(dataItem[x].Class);
alert(dataItem[x].SubjectName);
}
Thanks in advance
What you have there is not JSON, maybe because you've already parsed it. You have is an array consisting of a single object, with names for its keys. Regardless, I'll show you how to access that data:
var data = dataItem[0];
for(name in data) {
alert(name);
alert(data[name].id);
alert(data[name].full_name);
}
for (var x in dataItem[0]) {
if (dataItem[0].hasOwnProperty(x)) {
console.log(x);
}
}
http://jsfiddle.net/B44LW/
If you want other properties, then you can use the bracket notation:
dataItem[0][x].id
Basically I am transforming a JSON result into html and using $.each it iterate through multiple keys. For example, I am pulling back facebook posts and iterating through the likes in that post.
The problem lies in the fact that when there are multiple "likes" everything works great! although when there is only 1 "like" the "source" key is removed from the result set and my javascript breaks because I expect it to be there. Any idea why the $.each is skipping a level for single nodes? The following is my code:
* JQUERY **
$.each(post.likes.item, function(i, like){
$(currentpost).find('div.cc_likes').append(like + ',');
console.log(like)
});
* JSON RESULT **
* Single Like
likes": {
"item": {
"source": {
"cta": "Mary Smith",
"url": "http:\/\/www.facebook.com\/",
"photo": {
"image": "https:\/\/graph.facebook.com\/"
}
}
},
Result in console:
Object
cta: "MaryAnn Smith"
photo: Object
url: "http://www.facebook.com/"
* Multiple Likes
"likes": {
"item": [
{
"source": {
"cta": "Bobby Carnes Sr.",
"url": "http:\/\/www.facebook.com",
"photo": {
"image": "https:\/\/graph.facebook.com\"
}
}
},
{
"source": {
"cta": "Jenna Purdy",
"url": "http:\/\/www.facebook.com\",
"photo": {
"image": "https:\/\/graph.facebook.com\"
}
}
},
{
"source": {
"cta": "Kevin Say",
"url": "http:\/\/www.facebook.com\",
"photo": {
"image": "https:\/\/graph.facebook.com\"
}
}
}
],
"count": "10",
"count_display": "10"
},
Result in console:
Object
source: Object
cta: "Kevin Smith"
photo: Object
url: "http://www.facebook.com/"
Since $.each() needs an array or array like object as argument, before using the object post.likes.item check if it is an array of not.
Following code will always pass an array to jQuery -
$.each([].concat(post.likes.item), function(i, like){
$(currentpost).find('div.cc_likes').append(like + ',');
console.log(like)
});
Explanation
[] is an empty array in JavaScript. Every array in JavaScript has a concat method.
[].concat(obj) concats obj to the empty array and returns an array.
if obj is not an array, result is [obj] which is an array with one item.
if obj is an array, then result is a deep copy of obj which is already an array.
More about concat method
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
That is the jquery code being run on your JSON return. What's happening is, when you are looking at multiple results, it is looping through the array, return each base level object. However, when you are running it on a single return, it is looping through the object properties(in this case, "source"), and returning the value of that property.
You have two choices here. You can either make sure single items are still put in an array, or you can do a check for single items on the client side. The way Moazzam Khan suggests is the best way to do it in most cases.