Get JSON values as an array in JavaScript [duplicate] - javascript

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 1 year ago.
I have JSON content as follows
jsonList = {
"0": {
"Name": "Virat Kohli",
"Runs": "6283",
"Matches": "207",
"Average": "37.39",
"Strike Rate": "129.94",
"Half Centuries": "42",
"Centuries": "5",
"Team": "Royal Challengers Bangalore"
},
"1": {
"Name": "Shikhar Dhawan",
"Runs": "5784",
"Matches": "192",
"Average": "34.84",
"Strike Rate": "126.64",
"Half Centuries": "44",
"Centuries": "2",
"Team": "Delhi Capitals"
},
"2": {
"Name": "Rohit Sharma",
"Runs": "5611",
"Matches": "213",
"Average": "31.17",
"Strike Rate": "130.39",
"Half Centuries": "40",
"Centuries": "1",
"Team": "Mumbai Indians"
},
"3": {
"Name": "Suresh Raina",
"Runs": "5528",
"Matches": "205",
"Average": "32.51",
"Strike Rate": "136.76",
"Half Centuries": "39",
"Centuries": "1",
"Team": "Chennai Super Kings"
}
}
I get the value of "Virat Kohli" as
name = jsonList[0].Name
I am working to get all the Names in one array and Runs in one array like
names = ['Virat Kohli','Shikhar Dhawan','Rohit Sharma','Suresh Raina']
runs = [6283,5784,5611,5528]
I know I can do this using for loop. But is there any other way that is more efficient than for loop?

First, transform that Obj into an array:
const arr = Object.values(jsonList)
Then, get the information you need by using .map function:
const names = arr.map(el=> el.Name)
const runs = arr.map(el=> el.Runs)

Related

Json array prints out as a string? Not array? [duplicate]

This question already has answers here:
How to compute the sum and average of elements in an array? [duplicate]
(35 answers)
Closed 1 year ago.
I'm currently getting my data from an API. It stores the weight log of animal checkups as shown below.
Currently I'm storing it in a html tag:
<h3 className='dogWeight'>Average: {item.weight}%</h3>
But it prints the numbers together as a string (i.e 100102103). Is there anyway I can add all numbers in the array to just show the Average?
{
"dog":[
{
"weight":[
"78",
"100",
"92",
"86",
"89",
"88",
"91",
"87"
],
"id":"1",
},
{
"weight":[
"75",
"89",
"95",
"93",
"99",
"82",
"89",
"76"
],
"id":"2",
},
You can loop over data.dog and reduce the weight values by accumulating the parsed integer weight values and dividing by the length of the weight array.
const data = {
"dog": [{
"id": "1",
"weight": [ "78", "100", "92", "86", "89", "88", "91", "87" ],
}, {
"id": "2",
"weight": [ "75", "89", "95", "93", "99", "82", "89", "76" ],
}]
};
const avg = vals => vals.reduce((sum, x) => sum + parseInt(x, 10), 0) / vals.length;
data.dog.forEach(({ id, weight }) =>
console.log(`ID: ${id}, Avg Weight: ${avg(weight).toFixed(2)}%`));
.as-console-wrapper { top: 0; max-heightL 100% !important; }

How to remove specific item from JSON object correctly in REACT js?

In REACT JS, I have a JSON object in state component "myrecords" where items are grouped by their Company Names and it has following format:
{
"Master Automotives": [
{
"SparePartID": "43",
"Name": "Oil and Lubricants",
"Price": "4500",
"VendorID": "48",
"CompanyName": "Master Automotives",
"Qty": 1,
"TotalPrice": "4500"
},
{
"SparePartID": "45",
"Name": "Lights",
"Price": "2300",
"VendorID": "48",
"CompanyName": "Master Automotives",
"Qty": 1,
"TotalPrice": "2300"
}
],
"Repair Solutions": [
{
"SparePartID": "47",
"Name": "Steering Wheel",
"Price": "1500",
"VendorID": "60",
"CompanyName": "Repair Solutions",
"Qty": 1,
"TotalPrice": "1500"
}
],
"FiveStar Automotives": [
{
"SparePartID": "51",
"Name": "Brakes",
"Price": "234",
"VendorID": "70",
"CompanyName": "FiveStar Automotives",
"Qty": 1,
"TotalPrice": "234"
},
{
"SparePartID": "53",
"Name": "Clutch",
"Price": "999",
"VendorID": "70",
"CompanyName": "FiveStar Automotives",
"Qty": 1,
"TotalPrice": "999"
},
{
"SparePartID": "55",
"Name": "LED",
"Price": "288",
"VendorID": "70",
"CompanyName": "FiveStar Automotives",
"Qty": 1,
"TotalPrice": "288"
}
]
}
Im using this method to remove a specific item from myrecords state whenever delete button against an item is clicked:
removeCartItem(CompanyName, sid,e)
{
const items = {...this.state.myrecords};
const j = items[CompanyName].findIndex(item => item.SparePartID === sid);
items[CompanyName].splice([j], 1);
this.setState({
myrecords: items
});
}
Im sending CompanyName, SparePartID as sid in parameters of function to perform delete.
It works Perfectly FINE and deletes the item on which I click.
But problem is if a Company has only 1 item and I delete it, then still the myreocords JSON Object contains that Company with an empty array(no items). Instead I wanted it to delete such a Company who has no Items left in it.
SO that myrecords state should have only those Companies Data whose items are present.
Please help me to solve this Problem.
You should to remove node if it have no items:
removeCartItem(CompanyName, sid,e) {
const items = {...this.state.myrecords};
const j = items[CompanyName].findIndex(item => item.SparePartID === sid);
items[CompanyName].splice([j], 1);
// rm company node if it have no items
if (items[CompanyName].length === 0) {
delete items[CompanyName]
}
this.setState({
myrecords: items
});
}

Get unique values from array of dictionaries and create a new dictionary

I have a JSON file that looks a little like this:
[{
"name": "Il Brigante",
"rating": "5.0",
"match": "87",
"cuisine": "Italian",
"imageUrl": "/image-0.png"
}, {
"name": "Giardino Doro Ristorante",
"rating": "5.0",
"match": "87",
"cuisine": "Italian",
"imageUrl": "/image-1.png"
}, {
"name": "Cosme",
"rating": "5.0",
"match": "87",
"cuisine": "Mexican",
"imageUrl": "/image-1.png"
}]
I am trying to loop through the array, identify distinct "cuisine"'s and then create a dictionary with the "name"'s as the value and the matches as an array which will be the key.
Here is an example:
{ Italian:
[{"name": "Il Brigante",
"rating": "5.0", etc},
{"name": "Giardino Doro Ristorante",
"rating": "5.0", etc}],
Mexican:
[{"name": "Cosme",
"rating": "5.0", etc}]
}
Would anyone know how to do this? Any help would be immensely appreciated. Thanks so much in advance!!
Cheers,
Theo
You could use Array.prototype.reduce to create your resulting object.
Array.prototype.reduce()
The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
Here is an example:
var data = [{
"name": "Il Brigante",
"rating": "5.0",
"match": "87",
"cuisine": "Italian",
"imageUrl": "/image-0.png"
}, {
"name": "Giardino Doro Ristorante",
"rating": "5.0",
"match": "87",
"cuisine": "Italian",
"imageUrl": "/image-1.png"
}, {
"name": "Cosme",
"rating": "5.0",
"match": "87",
"cuisine": "Mexican",
"imageUrl": "/image-1.png"
}]
var res = data.reduce(function(a, b) {
if(a[b['cuisine']]) {
a[b['cuisine']].push( {name: b['name'], rating: b['rating']} )
} else {
a[b['cuisine']] = [ {name: b['name'], rating: b['rating']} ]
}
return a
}, {})
console.log(res)
I think you are going for this.
var byCuisine = {};
myJSON.map(function (obj) {
byCuisine[obj.cusine] = byCuisine[obj.cusine] || [];
//can clone it with JSON.parse(JSON.stringify( )) if you want then
// delete newObj.cuisine to get something like your structure above.
byCuisine[obj.cusine].push(obj);
})
You should also consider using `Array.prototype.forEach
const arr = [{
"name": "Il Brigante",
"rating": "5.0",
"match": "87",
"cuisine": "Italian",
"imageUrl": "/image-0.png"
}, {
"name": "Giardino Doro Ristorante",
"rating": "5.0",
"match": "87",
"cuisine": "Italian",
"imageUrl": "/image-1.png"
}, {
"name": "Cosme",
"rating": "5.0",
"match": "87",
"cuisine": "Mexican",
"imageUrl": "/image-1.png"
}];
const finalObj = {};
arr.forEach( obj => {
if ( ! finalObj[obj.cuisine] ) {
let arr = [];
arr.push(obj);
Object.assign(finalObj, {
[obj.cuisine]: arr
})
} else {
finalObj[obj.cuisine].push(obj)
}
});
console.log(finalObj);
This code declares a global const variable finalObj to hold your desired output.
the arr array of object is been looped in other to get all of it's elements which are objects, then we determine if obj.cusisine exists on the finalObj ( which it does not at the first instance a unique obj.cuisine is seen ). An array is created to hold the value of the entire obj value

C# Serialize Dictionary JSON

I am trying to serialize a dictionary in C# using JSON.NET and then consume it in a web application. This is the format I am returned but am unable to use it as I do not think it is in the correct format. I have tried the following:
Dictionary Serialization:
[JsonExtensionData]
public static Dictionary<string, object> objectDictionary = new Dictionary<string, object>();
string parametersJSON = JsonConvert.SerializeObject(objectDictionary, Formatting.Indented);
var x = get.getData;
x.p11.Name
{
"p11": {
"Name": "Parameter 1",
"Value": "1.00",
"Unit": "m",
"MinValue": "0.00",
"MaxValue": "5.00",
"Number": 11,
"DefaultValue": "0.00"
},
"p546": {
"Name": "Parameter 2",
"Value": "0.0000",
"Unit": "Hz",
"MinValue": "-480.000",
"MaxValue": "480.000",
"Number": 546,
"DefaultValue": "0.0000"
},
"p7": {
"Name": "Parameter 3",
"Value": "0.00",
"Unit": "Amps",
"MinValue": "0.00",
"MaxValue": "44.00",
"Number": 7,
"DefaultValue": "0.00"
}}
Nothing is wrong with your data:
var x = JSON.parse(jsonstr);
var name = x["p11"].Name;
For more information:
A Dictionary is parsed into an associative array (http://www.w3schools.com/js/js_arrays.asp)

Iterate over JSON AJAX response [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I need to go through each hotel key and go inside rates to retrieve some info, how could I get values of them inside this JSON on JavaScript:
[
{
"auditData": {
"processTime": "1545",
"timestamp": "2016-04-08 04:33:17.145",
"requestHost": "66.226.74.194",
"serverId": "sa37AUX3ROLBLIS.env",
"environment": "[int]",
"release": "2cb1bad878d2195c9b508e2007ef96616007dacb",
"internal": "bz66k2etuxrt5q5h2zyf3jf6|MX|03|HA|1|3|0|1|3|N|||||||||1"
},
"hotel": {
"checkIn": "2016-04-11",
"checkOut": "2016-04-12",
"code": 87399,
"name": "Premier",
"categoryCode": "3EST",
"categoryName": "3 ESTRELLAS",
"destinationCode": "MDF",
"destinationName": "Ciudad de Mexico",
"zoneCode": 10,
"zoneName": "Downtown",
"latitude": "19.431353",
"longitude": "-99.156457",
"rooms": [
{
"code": "DBL.2D",
"name": "DOBLE DOS CAMAS DOBLES",
"rates": [
{
"rateKey": "20160411|20160412|W|71|87399|DBL.2D|CGW-TODOS1|BB||1~2~1|2|N#-644903865",
"rateClass": "NOR",
"rateType": "BOOKABLE",
"net": "687.31",
"discount": "111.89",
"discountPCT": "14.00",
"sellingRate": "799.20",
"rateComments": "Incluye desayuno americano para adulto y menor\nel hotel no cuenta con aire acondicionado ",
"paymentType": "AT_WEB",
"packaging": false,
"boardCode": "BB",
"boardName": "ALOJAMIENTO Y DESAYUNO",
"cancellationPolicies": [
{
"amount": "799.20",
"from": "2016-04-08T23:59:00-05:00"
}
],
"rateBreakDown": {
"rateDiscounts": [
{
"code": "DN",
"name": "Descuento Niño",
"amount": "-281.68"
}
]
},
"rooms": 1,
"adults": 2,
"children": 1,
"childrenAges": "2",
"offers": [
{
"code": "9001",
"name": "Descuento niños",
"amount": "-281.68"
}
]
}
]
}
],
"totalSellingRate": "799.20",
"totalNet": "687.31",
"currency": "MXN"
}
},
{
"auditData": {
"processTime": "1543",
"timestamp": "2016-04-08 04:33:19.469",
"requestHost": "66.226.74.194",
"serverId": "sa3RKSJACHXE79K.env",
"environment": "[int]",
"release": "2cb1bad878d2195c9b508e2007ef96616007dacb",
"internal": "bz66k2etuxrt5q5h2zyf3jf6|MX|03|HA|1|3|0|3|3|N|||||||||1"
},
"hotel": {
"checkIn": "2016-04-11",
"checkOut": "2016-04-12",
"code": 87399,
"name": "Premier",
"categoryCode": "3EST",
"categoryName": "3 ESTRELLAS",
"destinationCode": "MDF",
"destinationName": "Ciudad de Mexico",
"zoneCode": 10,
"zoneName": "Downtown",
"latitude": "19.431353",
"longitude": "-99.156457",
"rooms": [
{
"code": "SGL.DB",
"name": "INDIVIDUAL CAMA DOBLE",
"rates": [
{
"rateKey": "20160411|20160412|W|71|87399|SGL.DB|CGW-TODOS1|BB||1~1~1|5|N#-644903865",
"rateClass": "NOR",
"rateType": "BOOKABLE",
"net": "687.31",
"discount": "111.89",
"discountPCT": "14.00",
"sellingRate": "799.20",
"rateComments": "Incluye desayuno americano para adulto y menor\nel hotel no cuenta con aire acondicionado ",
"paymentType": "AT_WEB",
"packaging": false,
"boardCode": "BB",
"boardName": "ALOJAMIENTO Y DESAYUNO",
"cancellationPolicies": [
{
"amount": "799.20",
"from": "2016-04-08T23:59:00-05:00"
}
],
"rateBreakDown": {
"rateDiscounts": [
{
"code": "DN",
"name": "Descuento Niño",
"amount": "-641.98"
}
]
},
"rooms": 1,
"adults": 1,
"children": 1,
"childrenAges": "5",
"offers": [
{
"code": "9001",
"name": "Descuento niños",
"amount": "-641.98"
}
]
}
]
}
],
"totalSellingRate": "799.20",
"totalNet": "687.31",
"currency": "MXN"
}
}
]
I was trying to use for (var key in data), where data is the JSON response from AJAX.
It's an array. You should iterate using a normal for loop, like
for(var i = 0; i < data.length;i++) {
var rooms = data[i].hotel.rooms
for(var j = 0; j < rooms.length; j++) {
var rates = rooms.rates .. //do something with rates, it's also an array
}
}
Use a each loop each time you see a [] the first character in the string is bracket so we do a each we select the child in our case "hotel" using dot notation v.hotel,v.hotel doesn't start with a bracket so we don't need a loop,we go down in the json object until we reach the rates key where we see another braket so we loop and select the child element in our case the rateKey
var obj =[
{
"auditData": {
"processTime": "1545",
"timestamp": "2016-04-08 04:33:17.145",
"requestHost": "66.226.74.194",
"serverId": "sa37AUX3ROLBLIS.env",
"environment": "[int]",
"release": "2cb1bad878d2195c9b508e2007ef96616007dacb",
"internal": "bz66k2etuxrt5q5h2zyf3jf6|MX|03|HA|1|3|0|1|3|N|||||||||1"
},...];
$.each(obj, function(i, v) {
$.each(v.hotel.rooms, function(i1, v1) {
$.each(v1.rates, function(i2, v2) {
console.log(v2.rateKey);
});
})
});
https://jsfiddle.net/78cpwq5g/
Use the Json object.
If suppose the values are stored in JsonObject.
And some values you may want to retrieve.
Eg:- "code": 87399,
"name": "Premier",
"categoryCode": "3EST",
"categoryName": "3 ESTRELLAS",
"destinationCode": "MDF",
"destinationName": "Ciudad de Mexico",
$(JsonObject).each(function(){
$(this).hotel.code;
$(this).hotel.name;
})

Categories

Resources