Displaying all keys value pair of array in nested json javascript - javascript

I have a JSON data from a URL and c am consuming it using jQuery ajax method.
Now as the JSON code below shows I have a DATA array containing objects in my JSON, now if I access FirstName using resp.DATA[0].FirstName, I am able to get it, but now I have to display all the key value pairs in DATA array and i don't know the key name i.e. I have to show every key and value.
There are two customers on data.
How can I do it either using JavaScript or jQuery?
JSON DATA:
{
"ERROR": [],
"DATA": [{
"CustomerID": "124",
"BranchID": "12",
"FirstName": "sandeep",
"LastName": "b",
"EmailID": "gggg#gmail.com",
"Sex": "Male",
"Landline": "",
"AlternateNumber": "",
"Password": "5735c2801",
"USERVARCHAR_2": ""
}],
"META": {
"totalPages": "1",
}
}
I have to display Key and value of each customer data in the form KEY:VALUE, so please suggest me how to loop this.

Use the for loop to iterate over javascript array literal
for (var key in resp.DATA) {
// skip loop if the property is from prototype
if (!resp.DATA.hasOwnProperty(key)) continue;
var objct = resp.DATA[key];
for (var prop in objct) {
// skip loop if the property is from prototype
if(!objct.hasOwnProperty(prop)) continue;
// your code
alert("The key is "+prop + "and the value is " + objct[prop]);
}
}
References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

Use Object.keys(object_name) to fetch all the keys of a Object.
The Object.keys() method returns an array of a given object's own
enumerable properties, in the same order as that provided by a
for...in loop (the difference being that a for-in loop enumerates
properties in the prototype chain as well).
for(var cust of resp.DATA){ // To iterate a array
for(var key in cust){ // To iterate a object ennumerable properties
console.log("Key is: "+key+" and Value is: "+cust[key]);
}
}

do this:
$(resp.DATA[0]).each(function(key, value){
// your code
});

Loop in to your array like this using .each()
$.each(your_array, function(key, value) {
alert('Array Key is: '+ key + ' \n Array Key value is: ' + value);
});
.each() Iterate over a jQuery object, executing a function for
each matched element.

Related

Iterate through object values - javascript

Given this data structure:
{ "name": [ "can't be blank" ], "league_id": [ "You already have a team in this league." ] }
How can I print this?
Can't be blank
You already have a team in this league
So basically I want to iterate through the values of the object. How can I do this with Javascript? Thank You!
Your data structure doesn't make much practical sense in that your property values are arrays with just one element in them. While legal, for the data you are showing, it makes more sense just to have the strings as the values.
Either way, a for/in loop over the object will allow you to iterate the keys.
With current structure:
let obj = {
"name": ["can't be blank"],
"league_id": ["You already have a team in this league."]
};
for(var key in obj){
console.log(obj[key][0]); // Here, you have to index the property value, which is an array
}
With arrays removed:
let obj = {
"name": "can't be blank",
"league_id": "You already have a team in this league."
};
for(var key in obj){
console.log(obj[key]); // Here, you can access the key value directly
}
You can also use Object.keys(obj), along with a .forEach() method call, which is a newer technique:
let obj = {
"name": ["can't be blank"],
"league_id": ["You already have a team in this league."]
};
Object.keys(obj).forEach(function(key){
console.log(obj[key][0]); // Here, you have to index the property value, which is an array
});
Let's see:
const obj = { "name": [ "can't be blank" ], "league_id": [ "You already have a team in this league." ] }
console.log(Object.values(obj).map(value => value.toString()).join("\n"))
Get values of the keys in object with Object.values method
map over them
Since the value itself is Array, cast it to string (or get the first element)
Join them with a new line

Efficient way to find name value pairs from JSON array in Javascript

I am currently making a call to a service which sends a response as an array of objects with name value pairs. An example of this can be seen below. There could be any amount of these name value pairs in any order but I just want to access the value for the name "name2". Is there an efficient way other than looping through each object and checking the name to obtain the corresponding value for name2?
[{"name":"name1","value":"value1"},{"name":"name2","value":"value2"}]
So from the above data set I would want an efficient way to search for name2 and get the corresponding value "value2".
Thanks
Unless you know the specific index of the object with the name name2 no.
You'll need to iterate until you find that name then you can bail out.
e.g.
var jsonData = [{"name":"name1","value":"value1"},{"name":"name2","value":"value2"}];
for(var i=0;i<jsonData.length;i++){
if(jsonData[i]['name'] == 'name2'){
console.log('The value is: ' + jsonData[i]['value']);
break;
}
}
Note that if you don't need to support Internet Explorer, you can use the Array.find() method to simplify this.
if you don't want to iterate over the array manually you can use lambda expression as the following
a =[{"name":"name1","value":"value1"},{"name":"name2","value":"value2"}] ;
//get the items that match your criteria
a.filter(item=>item.name=="name2")
//get those items' values
a.filter(item=>item.name=="name2").map(item=>item.value)
//get the first value (if you know that it's only one item that will match)
a.filter(item=>item.name=="name2").map(item=>item.value)[0]
You can use Array#find method.
var arr = [{
"name": "name1",
"value": "value1"
}, {
"name": "name2",
"value": "value2"
}];
// get the object containing name as `name2`
var obj = arr.find(function(v) {
return v.name === 'name2';
});
// get value property if object is defined
var res = obj && obj.value;
console.log(res)

For.. in loop - why does it work?

I am reading the book "JavaScript for web designers" and I've come to this example:
var fullName = {
"first": "John",
"last": "Smith"
};
for (var name in fullName) {
console.log(name + ": " + fullName[name]);
}
The output is:
"first: John"
"last: Smith"
What I don't get is: where do I tell the program to get the string "first" and "last". I mean, cycling the object "fullName", I fail to see how "name" can be related to "first" and "last". I hope this is clear.
Can you help? Many thanks!
for..in iterates over the keys of an object. You can then access an objects values by name using brackets.
var obj = {
a: 1,
b: 2,
c: 3
};
for (var key in obj) {
console.log('Key:', key);
console.log('obj[key] == obj["' + key + '"] == obj.' + key);
console.log('obj.' + key + ' == ' + obj[key]);
}
It's pretty simple to learn and/or understand. You're looping through all of the properties in the object fullName. For each property, you're giving it the temporary name/alias of name
So you could change it to for (var anything in fullName) and then in the body of the for loop you would reference each property by the name anything like so:
for (var anything in fullName) {
// anything is an alias for the current property your on of the object you're looping through
console.log(anything + ": " + fullName[anything]);
}
A for..in loop will iterate through the object's keys. If you use this on an array, then it (most browser engines) will convert the array into an object behind the scenes (read more on Dictionary Mode) and iterate the keys.
You can view the keys by using
var fullName = {
"first": "John",
"last": "Smith"
};
console.log(Object.keys(fullName));
And essentially the result of this call is then iterated. Keep in mind that using for..in does not guarantee order of the key value pairs.
in the above code name represent key of the object,
first and last are both keys in the object. and can be used to access the value in the object.
like in the first run of the loop it will be something like this
for("first" in fullName) {
console.log("first" + ": " + fullName["first"] //John);
}
When you loop through an object, you iterate through the keys. The keys of this object are first and last. Refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in for more information.

JavaScript - Check if a particular key is available in the JSON

I am retrieving JSON from a live streaming data.
For the first call I am getting dataset array with time and value. But in the second JSON dataset array is empty. I want to check if dataset array contains time key.
Retrieved JSON after first call:
{
"activities-heart-intraday": {
"dataset": [{
"time": "00:00:00",
"value": 91
}, {
"time": "00:01:00",
"value": 92
}, {
"time": "00:02:00",
"value": 92
}],
"datasetInterval": 1,
"datasetType": "second"
}
}
Retrieved JSON after second call:
{
"activities-heart-intraday": {
"dataset": [],
"datasetInterval": 1,
"datasetType": "second"
}
}
I am doing
var value = JSON.parse(data);
if (value.hasOwnProperty('time')) {
console.log("here");
}
to check if time key exists in the JSON, but it's not working.
How can I check if a particular key exists in the array in json?
Firstly you have to check that dataset is not an empty array. Then check that time is defined.
This can be solved with:
if (dataset[0] !== undefined && dataset[0].time !== undefined)
or just:
if (dataset[0] && dataset[0].time)
If you want to iterate through the array:
dataset.forEach(function (data) {
if (data.time) {
// your code
}
});
the data has a dataset array so we need to first check if the array is there and then if one of the arrays members has the time property
if( data.hasOwnProperty('dataset') && data.dataset.length != 0){
if( data.dataset[0].hasOwnProperty('time')){
console.log('true');
}
}
Since in JS you can not natively set and access object properties those with a "-" character in it by dot notation you have define them as strings and use bracket notation instead to set and access them. So you can make a check like this
data["activities-heart-intraday"].dataset.length > 0 && data["activities-heart-intraday"].dataset.every(e => !!e.time);
I can't really tell what data from your question is supposed to be but if it is the whole JSON object, then the most simple way is this:
if(data["activities-heart-intraday"]["dataset"][0]["time"])
console.log('time is set)
But beware! If for example the dataset is not set, you'll get an error that you are trying to get time key from undefined and the code will crash. I'd recommend using simple recursive function like this:
function is_there_the_key(json, keys){
if(keys.length == 0)
return true //we used the whole array, and every key was found
let key = keys.shift() //pop(get and remove) the first string from keys
if(!json[key]){
console.log(key + ' not found')
return false //one of the keys doesn't exist there
}
return is_there_the_key(json[key], keys)
}
Whether you return true or false, both of them will make their way up to the surface.
As the json parameter you pass the json you want to search in.
As the keys parameter you pass an array (mostly strings) of the keys in order they should go.
For example:
if(is_there_the_key(data, ["activities-heart-intraday", "dataset", 0, "time"])
//we found the key, do something here

How to print json data.

I have a json output array like this
{
"data": [
{
"name": "Ben Thorpe",
"id": "XXXXXXXXXXX"
},
{
"name": "Francis David",
"id": "XXXXXXXXXXX"
},
}
I want to loop through it and print out the all the names using javascript. I want to be able to do this.
for(i=0;i<length;i++){
var result += response.data[i].name + ', ';
}
But I am unable to find the length of the json object using javascript.
response.data is an array of objects, thus has a length property that you can use to iterate its elements.
var result;
for(var i=0;i<response.data.length;i++)
{
result += response.data[i].name + ', ';
}
If you just want to look at it for debugging purposes, do a console.log(myObject) or console.dir(myObject) and take a look at the firebug/chrome/safari console.
The object doesn't automatically have a length property because it's not an array. To iterate over properties of an object, do something like this:
for (var p in location) {
console.log(p + " : " + location[p]);
}
In some cases you may want to iterate over properties of the object, but not properties of the object's prototype. If you're getting unwanted stuff with the regular for..in loop, use Object.prototype's hasOwnProperty:
for (var p in location) if (location.hasOwnProperty(p)) {
console.log(p + " : " + location[p]);
}
The thing is, if this is/was really JSON data, it should have been a string at some point, as JSON is by definition a string representation of an object. So your question "How to print json data" almost reads like "How to print a string." If you want to print it out, you should be able to catch it before it gets to whatever parsed it into that object and just print it out.

Categories