My ajax call returns data like this:
{"result":[{"stats":{"min":{"caller_id.name":"Person1"},"count":"5"},"groupby_fields":[{"field":"caller_id","value":"ce4ddid73hes6e806d7070e21f961987"}]},{"stats":{"min":{"caller_id.name":"Person2"},"count":"2"},"groupby_fields":[{"field":"caller_id","value":"36ffbcfedbf9ba406d7070e21f96199c"}]},{"stats":{"min":{"caller_id.name":"Person3"},"count":"1"},"groupby_fields":[{"field":"caller_id","value":"714dd540dbefbe806d7070e21f96196a"}]},{"stats":{"min":{"caller_id.name":"Person4"},"count":"1"},"groupby_fields":[{"field":"caller_id","value":"ce4dd540dbefbe806d7070e21f961987"}]}]}
I then use var json = $.parseJSON(data); and get this (from the console log):
{result: Array(4)}
result:Array(4)
0:groupby_fields:Array(1)
0:{field: "caller_id", value: "ce4ddid73hes6e806d7070e21f961987"}
length:1
__proto__:Array(0)
stats:count:"5"
min:{caller_id.name: "Person1"}
__proto__:Object
__proto__:Object
1:{stats: {…}, groupby_fields: Array(1)}
2:{stats: {…}, groupby_fields: Array(1)}
3:{stats: {…}, groupby_fields: Array(1)}
length:4
__proto__:Array(0)
__proto__:Object
In previous calls I loop through the data to pull the values using something like this
var callerName = json[i]["caller_id.name"];
I'm not sure how to do it in this scenario.
I tried a few variations of the line above but didn't have any success.
I need to get the caller_id, count, and caller_id.name.
There are two types of structures in JSON: arrays [value1, value2] and objects {"key1":"value1", "key2":"value2"}.
In Javascript, you access:
array elements via array[index].
object properties via object.property or object['property']. The latter is required if the property name includes special characters.
You can chain these, so for instance you could write:
json.result[0].stats.min['caller_id.name']
json.result[0].stats.count
json.result[0].groupby_fields[0].field
json.result[0].groupby_fields[0].value
and so on.
This should't be difficult. Assuming the value of i is 0, here is the way by which you can get corresponding values:
let data = {
"result": [{
"stats": {
"min": {
"caller_id.name": "Person1"
},
"count": "5"
},
"groupby_fields": [{
"field": "caller_id",
"value": "ce4ddid73hes6e806d7070e21f961987"
}]
}, {
"stats": {
"min": {
"caller_id.name": "Person2"
},
"count": "2"
},
"groupby_fields": [{
"field": "caller_id",
"value": "36ffbcfedbf9ba406d7070e21f96199c"
}]
}, {
"stats": {
"min": {
"caller_id.name": "Person3"
},
"count": "1"
},
"groupby_fields": [{
"field": "caller_id",
"value": "714dd540dbefbe806d7070e21f96196a"
}]
}, {
"stats": {
"min": {
"caller_id.name": "Person4"
},
"count": "1"
},
"groupby_fields": [{
"field": "caller_id",
"value": "ce4dd540dbefbe806d7070e21f961987"
}]
}]
};
let i = 0;
console.log(data.result[i].stats.min['caller_id.name']);
console.log(data.result[i].stats.count);
console.log(data.result[i].groupby_fields[0].value);
I hope you can loop through data.result using a loop and provide specific values of i to the expressions.
To get the 'caller_id.name' key use
var json = {"result":[{"stats":{"min":{"caller_id.name":"Person1"},"count":"5"},"groupby_fields":[{"field":"caller_id","value":"ce4ddid73hes6e806d7070e21f961987"}]},{"stats":{"min":{"caller_id.name":"Person2"},"count":"2"},"groupby_fields":[{"field":"caller_id","value":"36ffbcfedbf9ba406d7070e21f96199c"}]},{"stats":{"min":{"caller_id.name":"Person3"},"count":"1"},"groupby_fields":[{"field":"caller_id","value":"714dd540dbefbe806d7070e21f96196a"}]},{"stats":{"min":{"caller_id.name":"Person4"},"count":"1"},"groupby_fields":[{"field":"caller_id","value":"ce4dd540dbefbe806d7070e21f961987"}]}]}
//json['result'][0]["stats"]["min"]['caller_id.name']
for (x in json['result']){ console.log(r['result'][x]["stats"]["min"]['caller_id.name'])}
result:
"Person1"
"Person2"
"Person3"
"Person4"
Related
I got JSON data, like:
{
"id": 1,
"active": true,
"dependency": [
{ "id": 2 }
{ "id": 3 }
]
},
{
"id": 2,
"active": true
},
{
"id": 3,
"active": true
}
I want to retrieve the "active" value for each dependency in the id 1 object. So far I used a forEach to get those dependency.
thisElement.dependency.forEach(function(id) {
console.log(id)
}
Which returns id 2 and id 3 as objects. Is there a way to use id.active straight away? By using only one loop? Because the result so far are objects without any connection to the related JSON data. Would it require to loop through the whole JSON data to retrieve those values?
The most efficient thing to to is create a hashmap with an Object or Map first so you only need to iterate the array once to find dependency related values.
You could do it by using Array#find() to search whole array each time but that is far more time complexity than the o(1) object lookup
const activeMap = new Map(data.map(obj => [obj.id, obj.active]))
data[0].dependency.forEach(({id}) => console.log(id ,' active: ' , activeMap.get(id)))
<script>
const data =
[
{
"id": 1,
"active": true,
"dependency": [
{"id": 2 },
{"id": 3}
]
},
{
"id": 2,
"active": false
},
{
"id": 3,
"active": true
}
]
</script>
I'm a beginner and would like to know how I can get a specific object from an array
I have an Array that looks like this:
data {
"orderid": 5,
"orderdate": "testurl.com",
"username": "chris",
"email": "",
"userinfo": [
{
"status": "processing",
"duedate": "" ,
}
]
},
To get the data from above I would do something like this:
return this.data.orderid
But how can I go deeper and get the status in userinfo?
return this.data.orderid.userinfo.status
doesn't work... anyone have any ideas?
A few points:
data is not an array, is an Object (see the curly braces, arrays have squared brackets). To be really precise, your syntax is invalid, but I assume you wanted to type data = { ... }, as opposed to data { ... }
Your syntax is almost correct, the only mistake you are making is that userinfo is an array, and arrays have numeric indexes (I.e. array[0], array[1]). What you are looking for is this.data.orderid.userinfo[0].status
Use data.userinfo[0].status to get the value (in your case this.data.userinfo[0].status)
var data = {
"orderid": 5,
"orderdate": "testurl.com",
"username": "chris",
"email": "",
"userinfo": [
{
"status": "processing",
"duedate": "" ,
}
]
};
console.log(data.userinfo[0].status);
User Info is an array, so you would need to access it using indexer like so:
return this.data.userinfo[0].status
MDN on arrays: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
You need to iterate over data.userinfo (it's an array)
var data = {
"orderid": 5,
"orderdate": "testurl.com",
"username": "chris",
"email": "",
"userinfo": [
{
"status": "processing",
"duedate": "" ,
}
]
};
data.userinfo.forEach(function(element) {
console.log(element.status);
});
There is an object where each key is an array of objects.
For example, in the following example data is an object having keys where each key is an array of object(s):
{
"status": 200,
"message": "Successful",
"data": {
"manual": [
{
"vendor_id": 1,
"price": 4590,
"discounts": {
"micro": 0,
"macro": 120
},
"vendor": "Vendor 1",
"customer_rating": "3.0/5",
"sla_compliance": 90,
"system_flag": "Green"
}
],
"nearest": [
{
"vendor_id": 1,
"price": 4590,
"discounts": {
"micro": 0,
"macro": 120
},
"vendor": "Vendor 1",
"customer_rating": "3.0/5",
"sla_compliance": 90,
"system_flag": "Green"
}
],
"auto": [
{
"vendor_id": 1,
"price": 4590,
"discounts": {
"micro": 0,
"macro": 120
},
"vendor": "Vendor 1",
"customer_rating": "3.0/5",
"sla_compliance": 90,
"system_flag": "Green"
}
],
"ticket_id": 72
}
}
I need to add/delete keys from the each object that is inside the array. For example, I need to add name key for each object inside the key manual. Likeways for other arrays of objects like nearest, auto. What would be the way to do this?
I tried to modify one key, and it changes the complete object. How could I avoid the reference thing here?
Do you mean something like this?
Say your data structure is called cars:
var cars = {
"status": 200,
"message": "Successful",
"data": {
"manual": [
{
...
Then you could add a property called name to the items under the property manual like
cars.data.manual = cars.data.manual.map(i => Object.assign({name: 'My ' + i.vendor}, i));
And similarly, to other items under different properties.
You can
console.log(cars);
afterwards to verify the result.
I'm running a node.js server that sends queries to an elasticsearch instance. Here is an example of the JSON returned by the query:
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 9290,
"max_score": 0,
"hits": []
},
"suggest": {
"postSuggest": [
{
"text": "a",
"offset": 0,
"length": 1,
"options": [
{
"text": "Academic Librarian",
"score": 2
},
{
"text": "Able Seamen",
"score": 1
},
{
"text": "Academic Dean",
"score": 1
},
{
"text": "Academic Deans-Registrar",
"score": 1
},
{
"text": "Accessory Designer",
"score": 1
}
]
}
]
}
}
I need to create an array containing each job title as a string. I've run into this weird behavior that I can't figure out. Whenever I try to pull values out of the JSON, I can't go below options or everything comes back as undefined.
For example:
arr.push(results.suggest.postSuggest) will push just what you'd expect: all the stuff inside postSuggest.
arr.push(results.suggest.postSuggest.options) will come up as undefined even though I can see it when I run it without .options. This is also true for anything below .options.
I think it may be because .options is some sort of built-in function that acts on variables, so instead of seeing options as JSON and is instead trying to run a function on results.suggest.postSuggest
arr.push(results.suggest.postSuggest.options)
postSuggest is an array of object.options inside postSuggest is also array of object. So first you need to get postSuggest by postSuggest[0] and then
postSuggest[0].options to get array of options
This below snippet can be usefule
var myObj = {..}
// used jquery just to demonstrate postSuggest is an Array
console.log($.isArray(myObj.suggest.postSuggest)) //return true
var getPostSuggest =myObj.suggest.postSuggest //Array of object
var getOptions = getPostSuggest[0].options; // 0 since it contain only one element
console.log(getOptions.length) ; // 5 , contain 5 objects
getOptions.forEach(function(item){
document.write("<pre>Score is "+ item.score + " Text</pre>")
})
Jsfiddle
I'm trying to figure out how to format this json in angular this is the result from extending all models from multiple forms.
{
"identifications": {},
"insurances": [
{
"insurances": [
{
"category": "",
"compName": "",
"planType": "",
"note": ""
}
]
}
],
"medical": {
"doctors": [
{
"doctors": [
{
"firstname": "James"
"note": "James Bond Note"
},
{
"firstname": "Robin",
"note": "Lorem Ipsum Dolor"
}
]
}
],
"records": {}
}
Here's I need to achieve to insert it into the API.
{
"parent_id": 17,
"insurances": [{
"insurance_type": "",
"notes": ""
}],
"medical": {
"doctors": {},
"blood": {},
},
"records": {}
}
If you're really looking at just pretty-printing stuff, investigate JSON.stringify:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
If you're trying to change the object from one data representation to another (I'll note that the second object is structurally different from the first, not just a matter of whitespace), then you just need to write some javascript that does stuff like new.doctors = old[0].medical[1].doctors (example, not actual code)
This question is pretty old, but nowadays you should use the json filter. For example:
var data = {a: 1, b: 2};
Then in the template:
{{ data|json:2 }}
Should output
{
a: 1,
b: 2
}