I have a json that I'd like to parse based on the 'zone' field in order to get a list of region etc through a select input.
var data = {
"zone01": [{
"region": "North",
"state": "New York",
"county": "Albany",
"code": "01"
}, {
"region": "North",
"state": "New York",
"county": "Albany",
"code": "05"
}, {
"region": "North",
"state": "Maine",
"county": "Auburn",
"code": "07"
}],
"zone02": [{
"region": "South",
"state": "Florida",
"county": "Gainseville",
"code": "82"
}, {
"region": "South",
"state": "Florida",
"county": "Macclenny",
"code": "73"
}]
};
I can parse it by using:
function setValues(range, zone, region, state, country){
if(range === 'zone'){
var getRegions = _.groupBy(data.zone02, 'region');
$.each(getRegions, function(k, v){
var region = JSON.stringify(k);
region = region.replace(/"/g,'');
$('select#region').append('<option value="'+region+'">'+region+'</option>');
});
}
}
But what I really need is _.groupBy(data.zone02, 'region') with data.zone02 being data + the function's variable zone
UPDATE
Here's my finished product, sans readability and re-usability: jsFiddle
Use bracket notation to reference a property using a variable.
data[zone]
Related
Currently I have an array of object which needs to be converted into hierarchy based on there key values. I am using reduce to achieve this , I was able to group on the 1st level of key (AREA) but I want it to happen recursively for other fields too and end result should be an hierarchy which looks like bellow , my hierarchy is huge but for example here I am taking 3 levels
Bellow is my array of object JSON
[{
"AREA": "EMEA",
"SUPER_REGION": "West Mediterranean Region",
"STATE": "Portugal",
},
{
"AREA": "USAC",
"SUPER_REGION": "United States",
"STATE": "california",
},
{
"AREA": "USAC",
"SUPER_REGION": "United States",
"STATE": "Texas",
},
{
"AREA": "ASIA",
"SUPER_REGION": "Japan",
"STATE": "Japan",
},
{
"AREA": "EMEA",
"SUPER_REGION": "North Europe Region",
"STATE": "ECOE",
},
{
"AREA": "USAC",
"SUPER_REGION": "United States",
"STATE": "Georgia",
}]
Expected result
[{
"EMEA": {
"West Mediterranean Region": {
"Portugal": null
},
"North Europe Region": {
"ECOE": null
}
}
},
{
"USAC": {
"United States": {
"Georgia": null
},
"United States": {
"Texas": null
},
"United States": {
"california": null
}
}
},
{
"ASIA": {
"Japan": {
"Japan": null
}
}
}]
code I have tried so far :
const result = data.reduce((grouped_Data, hierarchy) => {
const region = hierarchy["AREA"];
if (grouped_Data[region] == null) grouped_Data[region] = [];
grouped_Data[region].push(hierarchy);
return grouped_Data;
}, {});
You could reduce with each AREA as the key in the accumulator and group at each level
const input = [{AREA:"EMEA",SUPER_REGION:"West Mediterranean Region",STATE:"Portugal"},{AREA:"USAC",SUPER_REGION:"United States",STATE:"california"},{AREA:"USAC",SUPER_REGION:"United States",STATE:"Texas"},{AREA:"ASIA",SUPER_REGION:"Japan",STATE:"Japan"},{AREA:"EMEA",SUPER_REGION:"North Europe Region",STATE:"ECOE"},{AREA:"USAC",SUPER_REGION:"United States",STATE:"Georgia"}];
const grouped = input.reduce((acc, { AREA, SUPER_REGION, STATE }) => {
acc[AREA] ??= { [AREA]: {} }
acc[AREA][AREA][SUPER_REGION] ??= { }
acc[AREA][AREA][SUPER_REGION][STATE] = null
return acc;
}, {})
console.log(
Object.values(grouped)
)
I am working on Postman to verify some API calls, upon which I have gone through one of the end point, whose response is give below, and I need to make sure that within that JSON response:
[
{
"contact": {
"id": "k72yk2iwrf",
"firstName": "Francis",
"lastName": "Abell",
"title": "Translational Science Project Manager",
"company": "Sensei",
"email": "aa#aa.cpom",
"fax": {},
"businessAddress": {
"line1": "road",
"line2": "Street",
"line3": "Suite 710",
"city": "Boston",
"country": "US",
"postalCode": "02210",
"state": "MA"
},
"businessPhone": {
"number": "123-123-1234",
"ext": ""
},
"homeAddress": {},
"homePhone": {},
"mobilePhone": {}
},
"registration": {
"id": "104656",
"badgeId": "9208113975",
"eventId": "TESTLIBRA-10"
}
},
{
"contact": {
"id": "w4c4f2i7l4",
"firstName": "Francis",
"lastName": "Abell",
"title": "Translational Science Project Manager",
"company": "Sensei",
"email": "aa#aa.cpom",
"fax": {},
"businessAddress": {
"line1": "road",
"line2": "Street",
"line3": "Suite 710",
"city": "Boston",
"country": "US",
"postalCode": "02210",
"state": "MA"
},
"businessPhone": {
"number": "123-123-1234",
"ext": ""
},
"homeAddress": {},
"homePhone": {},
"mobilePhone": {}
},
"registration": {
"id": "104656",
"badgeId": "6803424516",
"eventId": "TESTLIBRA-10"
}
}
]
I can make sure that "eventId" is displaying and it is displaying "TESTLIBRA-10" value.
No matter, how long JSON response is, It can verify that this property , along with that value of that property are displaying.
I got my answer by myself, what I did was:
var jsonArrayData = pm.response.json();
pm.test('EventID property is displaying throughout JSON', function(){
jsonArrayData.each(function(eventID){
pm.expect(eventID.registration).to.have.property("eventId")
})
})
pm.test('Entered Libra EventID is entered', function(){
jsonArrayData.each(function(eventID){
pm.expect(eventID.registration.eventId).to.eql("TESTLIBRA-10")
})
})
Current format:
{
"SD": {
"Key": "SD",
"City": "San Diego",
"Name": "Padres"
},
"WSH": {
"Key": "WSH",
"City": "Washington",
"Name": "Nationals"
}
}
Expected format:
[
{
"Key": "SD",
"City": "San Diego",
"Name": "Padres"
},
{
"Key": "WSH",
"City": "Washington",
"Name": "Nationals"
}
]
You can do that with Object.values(...) which makes an array out of all the values from your object:
const obj = {
"SD": {
"Key": "SD",
"City": "San Diego",
"Name": "Padres"
},
"WSH": {
"Key": "WSH",
"City": "Washington",
"Name": "Nationals"
}
}
console.log(Object.values(obj));
It looks like Object.values is the answer, you can use it like this.
Object.values(your_object)
And it will return your expected format, here is the documentation on how it works if you would like to read further.
Object.values Documentation
How can I get the "name" of the following JSON object?
"location": {
"name": "Hilden",
"country": "Germany",
"region": "Nordrhein-Westfalen",
"lat": "51.167",
"lon": "6.933",
"timezone_id": "Europe/Berlin",
"localtime": "2020-04-22 15:03",
"localtime_epoch": 1587567780,
"utc_offset": "2.0"
}
["name"] returns the followin error
TypeError: Cannot read property 'name' of undefined
This could help you if not then let me know. If your json object is same as your_json_obj then you have to parse it first using JSON.parse(your_json_obj). If not then you simply use your_json_obj.location.name
const your_json_obj = "{
"location": {
"name": "Hilden",
"country": "Germany",
"region": "Nordrhein-Westfalen",
"lat": "51.167",
"lon": "6.933",
"timezone_id": "Europe/Berlin",
"localtime": "2020-04-22 15:03",
"localtime_epoch": 1587567780,
"utc_offset": "2.0"
},
...}"
const name = JSON.parse(your_json_obj).location.name
console.log(name)
You can access its properties using location.name, location["name"], for example:
const location = {
"name": "Hilden",
"country": "Germany",
"region": "Nordrhein-Westfalen",
"lat": "51.167",
"lon": "6.933",
"timezone_id": "Europe/Berlin",
"localtime": "2020-04-22 14:44",
"localtime_epoch": 1587566640,
"utc_offset": "2.0"
}
location.name;
location.["name"]
If you want to use it from the JSON object:
var y = '{"location": { "name": "Hilden", "country": "Germany", "region": "Nordrhein-Westfalen", "lat": "51.167", "lon": "6.933", "timezone_id": "Europe/Berlin", "localtime": "2020-04-22 15:03", "localtime_epoch": 1587567780, "utc_offset": "2.0" }}';
JSON.parse(y).location.name
So, in this case, you should use JSON.parse(jsonObject)) before access its properties. BUT NOTICE: "Make sure the text is written in JSON format, or else you will get a syntax error.", a "large text" inside {} - https://www.w3schools.com/js/js_json_parse.asp
I have a nested json. I want to post it as a form input value.
But, seems like jquery puts "Object object" string into the value.
It seems easier to pass around the string and convert into the native form I need, than dealing with json as I don't need to change anything once it is generated.
What is the simplest way to convert a json
var json = {
"firstName": "John",
"lastName": "Smith",
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
},
"phoneNumber": [
{ "type": "home", "number": "212 555-1234" },
{ "type": "fax", "number": "646 555-4567" }
],
"newSubscription": false,
"companyName": null
};
into its string form?
var json = '{
"firstName": "John",
"lastName": "Smith",
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
},
"phoneNumber": [
{ "type": "home", "number": "212 555-1234" },
{ "type": "fax", "number": "646 555-4567" }
],
"newSubscription": false,
"companyName": null
}'
Following doesn't do what I need:
Json.stringify()
jQuery doesn't have a method for JSON stringifying native objects. You will need json2.js which will provide the JSON.stringify() method to browsers that don't already support it.