I want to get the nested data in officeid id , code ,name ,shortname, accroym . and put it into individual variable.
How to I do that ???
My code:
{
"id": 1,
"code": "1000-001-1-01-001-001",
"name": "PEACE AND ORDER PROGRAM",
"isActive": true,
"majorFinalOutput": null,
"officeId": 1,
"office": {
"id": 1,
"code": "1-01-001",
"name": "Office of the Governor",
"shortName": "PGO",
"accronym": "PGO",
"website": null,
"email": null,
"telephone": null,
"fax": null,
"type": "1"
},
"sectorId": 1,
"sector": {
"id": 1,
"name": "General Public Services Sector",
"code": "1000",
"parentId": null,
"parent": null
},
"dateCreated": "2018-10-02T14:23:04.913",
"dateModified": null,
"createdBy": null,
"modifiedBy": null
}
getProgram() {
return this.httpClient.get('api/programs/' + idhold).subscribe((holdprogram: any[]) => {
console.log(holdprogram);
});
return this.programService.editProgram().finally( () => {
}).subscribe((holdprogram: any[]) => {
console.log(holdprogram);
console.log(holdprogram.office.id);
console.log(holdprogram.office.name);
console.log(holdprogram.office.shortname);
}, error => {
console.error(error);
},
() => {
});
}
The usual simplest way to keep a reference to a variable obtained via a request is to use a component variable :
in the component :
public export class MyComponent {
...
public office: any; // instead of using 'any', you could create an interface corresponding to the structure
...
}
in the subscribe :
.subscribe((holdprogram: any[]) => {
this.office = holdprogram.office;
console.log(this.office);
// now this.office keeps a reference of your nested variable 'office'.
},
If you need to keep a reference for it across components, it's a bit more comlicated : you could do something similar at the service level (using tap and a local variable), and you'll need to add some more "cache handling" mechanism.
Related
I'm trying to create a function that will retrieve some objects for my in a very specific format. Here's the code for that function:
pool.getConnection(function(err, connection) {
if (err) {
return res.status(500).json({
success: false,
data: err
});
}
connection.query("select cqq.* from coursequizquestions as cqq, coursequiz as cq where cqq.quiz = ? and cq.quizTitle = cqq.quiz and cq.course in (select courseUUID from courses where courseName = ?)", [quizName, courseName], function(err1, results) {
connection.release();
if (err1) {
return res.status(500).json({
success: false,
data: err1
});
}
let r = {};
for(const i in results) {
r[results[i].quizQuestion] = results[i];
}
return res.status(201).json({
success: true,
data: r
});
});
})
Where "pool" is an SQL pool object created using the mysql.createpool function. When I request this data, I'm expecting to get something that looks like this:
{
"Question 1": {
"id": 1,
"quiz": "Vue.js Introduction",
"quizQuestion": "Question 1",
"quizAnswer": null,
"dateCreated": "2021-06-17T04:00:00.000Z",
"deletedDate": null,
"videoUUID": null,
"questionScore": 50,
"questionOrder": 1,
"type": "Input"
},
"Question 2": {
"id": 2,
"quiz": "Vue.js Introduction",
"quizQuestion": "Question 2",
"quizAnswer": null,
"dateCreated": "2021-06-17T04:00:00.000Z",
"deletedDate": null,
"videoUUID": null,
"questionScore": 50,
"questionOrder": 2,
"type": "Input"
}
}
and it seems like it is exactly what I get when monitoring from the backend. When it arrives on the frontend, however, I get this:
{
"0": {
"questionOrder": 1,
"type": "input",
"quizQuestion": "0",
"questionScore": 50,
"dateCreated": "2021-06-17",
"deletedDate": null,
"videoUUID": null,
"choices": {}
},
"1": {
"questionOrder": 2,
"type": "input",
"quizQuestion": "1",
"questionScore": 50,
"dateCreated": "2021-06-17",
"deletedDate": null,
"videoUUID": null,
"choices": {}
},
"Question 1": {
"id": 1,
"quiz": "Vue.js Introduction",
"quizQuestion": "Question 1",
"quizAnswer": null,
"dateCreated": "2021-06-17T04:00:00.000Z",
"deletedDate": null,
"videoUUID": null,
"questionScore": 50,
"questionOrder": 1,
"type": "Input"
},
"Question 2": {
"id": 2,
"quiz": "Vue.js Introduction",
"quizQuestion": "Question 2",
"quizAnswer": null,
"dateCreated": "2021-06-17T04:00:00.000Z",
"deletedDate": null,
"videoUUID": null,
"questionScore": 50,
"questionOrder": 2,
"type": "Input"
}
}
There are added keys that are integers as if my object was an array. I don't see this type of output at any other endpoint. Oddly, when I log this object (in Google Chrome) the integer keys do not appear in the preview, but they do appear when I expand the entire object. Also, when I loop over this object using this code:
fetch("http://localhost:3000/api/courses/getQuestions?quizName=" + encodeURI(document.getElementById("quiz_title").value) + "&courseName=" + encodeURI(course)).then(j => j.json())
.then(j => {
console.log(j.data);
questionData = j.data;
let questionList = document.getElementById("question-list");
questionList.innerHTML = "";
for (const i in sortDict(questionData, "questionOrder")) {
makeQuestionElement(i, questionList);
}
}
then it only loops over the integer keys, essentially ignoring the portion of the output that was expected. Is there any insight as to what's happening here?
I've solved this problem - It turns out that my sortDict function was implemented incorrectly. Instead of returning an object with sorted keys, it returned a list of keys in the sorted order. The reason that the keys were populating like an array is that I was actually iterating through an array when running my loop. I've adjusted the code with this information in mind, and the problem was fixed.
I have a component of vuejs and my problem is that when I want a roles.name Roles works, but I don't want all JSON.
A example of JSON:
{
"id_role": 2,
"name": "Prova",
"email": "prova#prova.com",
"email_verified_at": null,
"created_at": "2021-03-01T09:39:42.000000Z",
"updated_at": "2021-03-01T09:39:42.000000Z",
"roles": [
{
"id": 2,
"name": "infomanager",
"guard_name": "web",
"created_at": "2021-03-01T09:39:42.000000Z",
"updated_at": "2021-03-01T09:39:42.000000Z",
"pivot": {
"model_id": 4,
"role_id": 2,
"model_type": "App\\Models\\User"
}
}
]
}
And this is component of vuejs:
export default {
data() {
return {
items: [],
sortBy: '',
sortDesc: false,
output: null,
// Note 'isActive' is left out and will not appear in the rendered table
fields: [
{
key: 'name',
label: 'Nom Usuari',
sortable: true
},
{
key: 'roles.name',
label: 'Nom Rols',
sortable: true
},
{
key: 'actions',
label: 'Accions'
}
],
}
},
My question is how am I down level, roles.name doesn't work.
Thank you so much!!
If I understand your question, you want to replace your roles array-of-objects to an array which holds only roles.name field.
In this case you can use flatMap method from lodash library.
Assume that your JSON is assigned into a variable called rolesJson, it will look like that:
let rolesJson = {
"id_role": 2,
"name": "Prova",
"email": "prova#prova.com",
"email_verified_at": null,
"created_at": "2021-03-01T09:39:42.000000Z",
"updated_at": "2021-03-01T09:39:42.000000Z",
"roles": [
{
"id": 2,
"name": "infomanager",
"guard_name": "web",
"created_at": "2021-03-01T09:39:42.000000Z",
"updated_at": "2021-03-01T09:39:42.000000Z",
"pivot": {
"model_id": 4,
"role_id": 2,
"model_type": "App\\Models\\User"
}
}
]
};
// create a new attribute with the flatted roles array
rolesJson.flatted_roles = _.flatMap(rolesJson.roles, el => {
return el.name;
});
// remove the original roles array
delete rolesJson.roles;
I have a JSON file with a list of products in my back-end ( Spring ). I want to be able to pass the content to the front-end ( in Angular ).
I have a JSON file in an assets folder in my front-end made with angular.
This is the JSON file:
[ {
"brand": "",
"category": {
"id": 29,
"name": "hand held"
},
"description": "New D131 Scanner complete",
"hidden": false,
"id": 10,
"image": null,
"productNumber": "E14NO1617",
"quantity":1
},
{
"brand": "",
"category": {
"id": 29,
"name": "hand held"
},
"description": "New D132 Scanner complete",
"hidden": false,
"id": 10,
"image": null,
"productNumber": "E14NO1617",
"quantity":1
},
{
"brand": "",
"category": {
"id": 50,
"name": "card reader"
},
"description": "USB,
"hidden": false,
"id": 26,
"image": null,
"productNumber": "ST-1044UB",
"quantity": 1
}
]
I then display the objects ( products in my case ) on a table with the following function in the service:
getTemplates() : Promise<Product[]> {
return this.http.get<Product[]>("http://localhost:4200/assets/BirdyProducts.json")
.toPromise();
}
This works exactly like I want it to be displayed,
But I don't want to store the the JSON in my front-end assets folder.
I want it to be in my back-end in a resources folder and send the file with a rest-controller and still get the same result.
I tried a lot with Objectmapper, JSONObjects,... but did not find a solution.
#Controller
public class BirdyProductsController {
#RequestMapping(
value = "/birdyProducts",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE
)
String getBirdyProducts() {
return "json/BirdyProducts.json";
}
}
This worked for me.
Path to JSON file: \src\main\resources\static\json\BirdyProducts.json
#RestController
#RequestMapping
public class ExampleController {
#GetMapping("/BirdyProducts")
public InputStreamResource getJsonFile() throws IOException {
return new InputStreamResource(new ClassPathResource("/assets/BirdyProducts.json").getInputStream());
}
}
When I request for http://localhost:8080/BirdyProducts I get the content of the file.
The file is in the \src\main\resources\assets folder on the backend side.
So quite new to React here (mostly backend and devops engineer). I need to fix a bug as the person usually responsible is not available currently.
One of the REST endpoint is formatting dates incorrectly while sending the data to the backend. The data expected from the endpoint for a PUT is
"items": [
{
"uuid": "abc7aba1-47ad-46d1-a3a5-d26ff55e4cf8",
"item_id": "21626227",
"item_description": "Test",
"item_schedule": {
"uuid": "37f8ca4c-6469-4bfb-822e-acfbc02e502e",
"start_date": "2018-12-04",
"end_date": "2018-12-06",
"interval": 3,
"unit": "days",
"occurrence": 1
"schedule_dates": [
{
"uuid": "d5b73ac5-be77-40c5-b11b-45034f70f81f",
"planned_date": "2018-12-04",
"custom": true
}
]
}
},
{
"uuid": "7abca4f4-1717-4136-aec6-3a37b4971c81",
"item_id": "21626229",
"item_description": "Test 2",
"maintenance_plan": "31001827",
"item_schedule": {
"uuid": "5de45d6e-81e8-4c86-9eb2-31c71089c876",
"start_date": null,
"end_date": null,
"interval": null,
"unit": "",
"occurrence": null,
"schedule_dates": [
{
"uuid": "da7ed2e4-053e-4f1d-80ca-2d6d258e8a08",
"planned_date": "2018-12-13",
"custom": true
}
]
}
}
]
Instead what we get for all the dates, i.e. start_date, end_date and planned_dates is (skipping all the right stuff here..)
"end_date": "2018-12-05T13:00:00.000Z",
"start_date": "2018-12-03T13:00:00.000Z"
"planned_date" : "2018-12-03T13:00:00.000Z"
When creating a new schedule for a new item, the old schedule data is incorrectly formatted.
I have tried to loop over all the items and the relevant schedule and dates and correctly format them , but doesn't seem to work.
Do I need to use map here instead of foreach?
const mapDispatchToProps = (dispatch, props) => ({
save: (value, notes) => dispatch(ItemDetailAction.saveLocal(
props.value.merge(
Map(Object.assign(
{
notes: notes.setIn([0, 'created'], undefined),
uuid: props.value.get('uuid'),
},
props.value.getIn(['item', 'type']) === 'P' && {
items: props.value
.get('items').forEach((item) => {
console.log(item.get('item_schedule'));
const start_date = item.get('item_schedule').get('start_date');
if (start_date !== '') {
const formatted_date = moment(start_date).format('YYYY-MM-DD');
//not updating the date-format below in the same array.
item.get('item_schedule').set('start_date',formatted_date);
item.setIn(['item_schedule', 'start_date'],formatted_date);
// this still prints the wrong date-format
console.log(item.get('item_schedule').get('start_date'));
}
}),
},
)),
),
true,
{
then: () => {
props.onCancel();
dispatch(actions.getItemListTable(FilterMaintenance.asParams(props.filters)));
},
}, )), });
I'm working in Symfony2 application and what I'm trying to do is to remove unwanted fields from response and show only fields that I want.
My JSON looks like this:
[
{
"id": 1,
"title": "Granit",
"typeId": {
"id": 1,
"name": "X or Y",
"acroname": "xory",
"__initializer__": null,
"__cloner__": null,
"__isInitialized__": true
},
"pushDate": {
"timezone": {
"name": "Europe/Berlin",
"location": {
"country_code": "DE",
"latitude": 52.5,
"longitude": 13.36666,
"comments": "most locations"
}
},
"offset": 7200,
"timestamp": 1460584800
},
"addedAt": {
"timezone": {
"name": "Europe/Berlin",
"location": {
"country_code": "DE",
"latitude": 52.5,
"longitude": 13.36666,
"comments": "most locations"
}
},
"offset": 7200,
"timestamp": 1460548644
},
"deviceToShow": {
"id": 2,
"name": "Mobile",
"__initializer__": null,
"__cloner__": null,
"__isInitialized__": true
},
"statusSurvey": false,
"slides": [
{
"id": 1,
"title": "First Question",
"picture1": "160413015724bazinga2.jpg",
"picture2": "160413015724th.jpg",
"idSurvey": 1,
"absolutePathpic1": "C:\\xampp\\htdocs\\stu-wrapper\\src\\AppBundle\\Entity/../../../web/uploads/slideSurvey/160413015724bazinga2.jpg",
"webPathpic1": "uploads/slideSurvey/160413015724bazinga2.jpg",
"absolutePathpic2": "C:\\xampp\\htdocs\\stu-wrapper\\src\\AppBundle\\Entity/../../../web/uploads/slideSurvey/160413015724th.jpg",
"webPathpic2": "uploads/slideSurvey/160413015724th.jpg",
"file": null,
"file1": null
}
],
"categories": []
}
]
I want to remove fields like "initializer": null,"cloner": null, "isInitialized": true and hide timezone object and show only "timestamp".
Here is my controller where I'm doing serializing and creating Json Response.
public function getAction()
{
$em = $this->getDoctrine ()->getManager ();
$survey = $em->getRepository ( 'AppBundle:Survey' )->findAll ();
if ( !$survey ) {
throw $this->createNotFoundException ( 'Data not found.' );
}
$encoder = new JsonEncoder();
$normalizer = new ObjectNormalizer();
$normalizer->setCircularReferenceHandler ( function ( $survey ) {
return $survey->getid ();
} );
$serializer = new Serializer( array ( $normalizer ), array ( $encoder ) );
$jsonContent = $serializer->serialize ( $survey, 'json' );
return new Response( $jsonContent );
}
Thank you.
Try to exclude this fields:
$normalilzer->setIgnoredAttributes(
[
"__initializer__",
"__cloner__",
"__isInitialized__"
]);
Detach entity to remove doctrine2 links to the object
$em->detach($survey);