iterate json array in javascript [duplicate] - javascript

This question already has answers here:
draw google graph from json [closed]
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Parse JSON in JavaScript? [duplicate]
(16 answers)
How do I enumerate the properties of a JavaScript object? [duplicate]
(14 answers)
Closed 8 years ago.
hi i have generated following json , can i iterate through this
i have validated this josn using some sites
following is just example there can be more section like MATHS, LOGICAL REASONING ,ENGLISH
they can also have their individual types
{ "MATHS": [
{
"Section": "MATHS",
"Type": "INCORRECT",
"Count": "5"
},
{
"Section": "MATHS",
"Type": "NOT SOLVED",
"Count": "20"
}
],
"LOGICAL REASONING": [
{
"Section": "LOGICAL REASONING",
"Type": "CORRECT",
"Count": "1"
},
{
"Section": "LOGICAL REASONING",
"Type": "INCORRECT",
"Count": "4"
},
{
"Section": "LOGICAL REASONING",
"Type": "NOT SOLVED",
"Count": "20"
}
]
}
i have searched on may question on stack overflow but none of them can help me

Your JSON has 2 top-level elements. So, you can't logically iterate across the entire document (without flattening it).
But you can iteration across the "MATHS" and "LOGICAL REASONING" elements.
For example, using underscore:
_(data.MATHS).each(function(item) {
var section = item.SECTION;
var type = item.TYPE;
var count = item.COUNT;
// Now do something with them
});
Note the different access method to the 'LOGICAL REASONING' element, because of the space.
_(data['LOGICAL REASONING').each(function(item) {
var section = item.SECTION;
var type = item.TYPE;
var count = item.COUNT;
// Now do something with them
});
If you wanted all the data together, one way of doing it would be:
var flattened = _.union(data.MATHS, data['LOGICAL REASONING']);
_(flattened).each(function(item) {
// Process...
});
Check out the underscore docs for some more information about the possibilities. Many ways to skin a cat.
http://underscorejs.org/
Cheers.

Related

Getting only requested item from every object Javascript [duplicate]

This question already has answers here:
Remove property for all objects in array
(18 answers)
How to get a subset of a javascript object's properties
(36 answers)
How to map more than one property from an array of objects [duplicate]
(7 answers)
Closed 2 years ago.
I am trying to figure out if I can send only relevant javascript info to the frontend from the backend because I want to hide things like ID, and others when my frontend makes a request.
To put things in perspective, here is a dummy code.
[
{
"_id": "215874514845452155",
"greeting":"Hello there"
},
{
"_id": "181474545841541515",
"greeting": "General Kenobi"
},
]
when requesting, I want to get result like:
[
{
"greeting": "Hello there"
},
{
"greeting": "General Kenobi"
},
]
I am still learning stuff and I know about loop function but I want to know if there is some neat trick to it. I am coming from R programming, we hate loops.
Use Array.prototype.map:
const input = [
{
"_id": "215874514845452155",
"greeting":"Hello there",
"other":"foo"
},
{
"_id": "181474545841541515",
"greeting": "General Kenobi",
"other":"bar"
},
];
const result = input.map(({greeting,other}) => ({greeting,other}));
console.log(result);
The above is a shorthand way of writing this:
const input = [
{
"_id": "215874514845452155",
"greeting":"Hello there",
"other":"foo"
},
{
"_id": "181474545841541515",
"greeting": "General Kenobi",
"other":"bar"
},
];
const result = input.map(x => {
return {
greeting: x.greeting,
other: x.other
}
});
console.log(result);

Sort Array of object by object field in Angular 6 [duplicate]

This question already has answers here:
Sort array of objects by string property value
(57 answers)
Closed 4 years ago.
I am getting an array of "product"s from a resolver getting data from a json endpoint.
ngOnInit() {
this.products = this._route.snapshot.data.products;
console.log('products: ', this.products);
}
where one of the objects in this array is in the format
{
"id": 3645,
"date": "2018-07-05T13:13:37",
"date_gmt": "2018-07-05T13:13:37",
"guid": {
"rendered": ""
},
"modified": "2018-07-05T13:13:37",
"modified_gmt": "2018-07-05T13:13:37",
"slug": "vpwin",
"status": "publish",
"type": "matrix",
"link": "",
"title": {
"rendered": "VPWIN"
},
"content": {
"rendered": "",
"protected": false
},
"featured_media": 0,
"parent": 0,
"template": "",
"better_featured_image": null,
"acf": {
"domain": "SMB",
"ds_rating": "3",
"dt_rating": ""
},
...
},
What I want to do is sort this array by the field title.rendered
In olden times, in AngularJS, I would simply use an orderBy pipe in the template set to this field. Apparently, this is removed in Angular and from doing research it seems the preferred method is to sort the data itself, such as in ngOnInit.
But I can't figure out how to sort products by producs.title.rendered.
You can simply use Arrays.sort()
array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));
Working Example :
var array = [{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"VPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""},},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"adfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"bbfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}}];
array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));
console.log(array);
Try this
products.sort(function (a, b) {
return a.title.rendered - b.title.rendered;
});
OR
You can import lodash/underscore library, it has many build functions available for manipulating, filtering, sorting the array and all.
Using underscore: (below one is just an example)
import * as _ from 'underscore';
let sortedArray = _.sortBy(array, 'title');
Not tested but should work
products.sort((a,b)=>a.title.rendered > b.title.rendered)

php merge two JSON arrays into one object [duplicate]

This question already has answers here:
Merging two json in PHP
(4 answers)
Closed 5 years ago.
I'm trying to merge two different json arrays into one object. The json arrays have different data (in terms of the data itself and the structure):
datafortable = [{"name": 3,"amount": "1190042293","category": "cars"}]
dataforchart = [{"name": 3,"amount": "5801"}]
What I would like to get is something like this:
datafortableandchart = {
"datafortable": [
{
"name": 3,
"amount": "1190042293",
"category": "cars"
}
],
"dataforchart": [
{
"name": 3,
"amount": "5801"
}
]
}
Then, in javascript I would like te be able to refer to the different json arrays like this:
dataprovider: datafortableandchart.datafortable
Is this possible?
First convert them to array then use array_merge to merge to arrays and again json_encode them
json_encode(array_merge(json_decode($datafortable , true),json_decode($dataforchart , true)))

Converting a JSON object to array? Read description [duplicate]

This question already has answers here:
Converting a JS object to an array using jQuery
(18 answers)
Closed 5 years ago.
my server upon request, serves JSON from a node mysql query, but only the names row. Example:
{
"Name": "Charles"
}, etc.
How can I, get the value of Name and put it into an array? say I have this,
[
{
"Name": "Charles"
},
{
"Name": "Alex"
}
]
how can I get, Charles and Alex, into an array?
Like:
Names = ["Charles", "Alex]?
You can make use of the map function. The map method creates a new array with the results of calling a provided function on every element in this array. In your case, you need to select only the Name.
var arr = [
{
"Name": "Charles"
},
{
"Name": "Alex"
}];
var names = arr.map(x=>x.Name)
console.log(names);

How to iterate JSON objects with JSON objects in every object (JavaScript)? [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
I have multiple JSON objects which are have multiple JSON objects.
Now how do i iterate the Objects in deep.
My JSON structure is like below.
{
"phanim": {
"msg1": {
"data": "Hii ra..",
"date": "Sep 9",
"sender": "Phani",
"type": "text"
},
"msg2": {
"data": "How r u?",
"date": "Sep 9",
"sender": "Phani",
"type": "text"
}
}
}
Probably a recursive function - check if the typeof the current iterated property is an object, if so, iterate that!
var iterateObj = function(obj) {
for (var key in obj) {
if (typeof obj[key] === "object") {
iterateObj(obj[key]);
} else {
console.log(obj[key]);
}
}
}
Note: this won't work if one of your properties is an array - you'll need an additional check and logic for that.

Categories