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++){}
Related
Using node.js(javascript) how do I access the GetDataResult node in this JSON data that has been converted from SOAP data.
{
"s:Envelope": {
"$": {
"xmlns:s": "http://schemas.xmlsoap.org/soap/envelope/"
},
"s:Body": [{
"GetDataResponse": [{
"$": {
"xmlns": "http://tempuri.org/"
},
"GetDataResult": ["You entered: TEST"]
}]
}]
}
}
Test using nodejs interactive mode :
$ node
> var x = {
... "s:Envelope": {
..... "$": {
....... "xmlns:s": "http://schemas.xmlsoap.org/soap/envelope/"
....... },
..... "s:Body": [{
....... "GetDataResponse": [{
......... "$": {
........... "xmlns": "http://tempuri.org/"
........... },
......... "GetDataResult": ["You entered: TEST"]
......... }]
....... }]
..... }
... }
undefined
> console.log(x["s:Envelope"]["s:Body"][0]["GetDataResponse"][0]["GetDataResult"][0])
Output :
'You entered: TEST'
Explanations :
I try to elaborate a bit from comments below. There is no container, I try to explain :
You have to think json like what it is : an object or a data structure.
In python, we would say it's a dict, in perl a hash table etc... Globally, it's all about associative array
So when you see in JSON :
"key" : { "value" }
it's an associative array
If instead you see
"key": [
{ "key1": "foo" },
{ "key2": "bar" },
{ "key3": "base" }
]
It's an array of hashes or array of associative arrays.
When you access a simple associative array without spaces or odd characters, you can (in js do :
variable.key
In your case, you have odd character : in the key name, so x.s:Envelope wouldn't work. Instead we write: x['s:Envelope'].
And as far as you have arrays of associative arrays inside [], you have to tell js which array number you need to fetch. It's arrays with only one associative array, so it's simple, we go deeper in the data structure by passing array number, that's what we've done with
x['s:Envelope']["s:Body"][0]
^
|
Let's say I have the next JSON file:
{
"shows": [
{
"name": "House of cards",
"rating": 8
},
{
"name": "Breaking bad",
"rating": 10
}
]
}
I want to access the rating of a show, by it's name. Something like this:
var rating = data.shows["House of cards"].rating;
Is this possible? Or something similar?
Thanks a lot!
You won't have such hash-style access just by deserializing that JSON sample.
Maybe you might be able to re-formulate how the data is serialized into JSON and use object literals even for shows:
{
"shows": {
"House of cards": {
"rating": 8
}
}
}
And you can still obtain an array of show keys using Object.keys(...):
Object.keys(x.shows);
Or you can even change the structure once you deserialize that JSON:
var x = { shows: {} };
for(var index in some.shows) {
x.shows[some.shows[index].name] = { rating: some.shows[index].rating };
}
// Accessing a show
var rating = x.shows["House of cards"].rating;
I suggest you that it should be better to do this conversion and gain the benefit of accessing your shows using plain JavaScript, rather than having to iterate the whole show array to find one.
When you use object literals, you're accessing properties like a dictionary/hash table, which makes no use of any search function behind the scenes.
Update
OP has concerns about how to iterate shows once it's an associative array/object instead of regular array:
Object.keys(shows).forEach(function(showTitle) {
// Do stuff here for each iteration
});
Or...
for(var showTitle in shows) {
// Do stuff here for each iteration
}
Update 2
Here's a working sample on jsFiddle: http://jsfiddle.net/dst4U/
Try
var rating = {
"shows": [
{
"name": "House of cards",
"rating": 8
},
{
"name": "Breaking bad",
"rating": 10
}
]
};
rating.shows.forEach(findsearchkey);
function findsearchkey(element, index, array) {
if( element.name == 'House of cards' ) {
console.log( array[index].rating );
}
}
Fiddle
var data = {"shows": [{"name": "House of cards","rating": 8},{"name": "Breaking bad","rating": 10}]};
var shows = data.shows;
var showOfRatingToBeFound = "House of cards";
for(var a in shows){
if(shows[a].name == showOfRatingToBeFound){
alert("Rating Of "+ showOfRatingToBeFound+ " is " +shows[a].rating);
}
}
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.
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