Posts

Showing posts with the label Object

Can I Loop Through A Javascript Object In Reverse Order?

Answer : Javascript objects don't have a guaranteed inherent order, so there doesn't exist a "reverse" order. 4.3.3 Object An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method. Browsers do seem to return the properties in the same order they were added to the object, but since this is not standard, you probably shouldn't rely on this behavior. A simple function that calls a function for each property in reverse order as that given by the browser's for..in, is this: // f is a function that has the obj as 'this' and the property name as first parameter function reverseForIn(obj, f) { var arr = []; for (var key in obj) { // add hasOwnPropertyCheck if needed arr.push(key); } for (var i=arr.length-1; i>=0; i--) { f.call(obj, arr[i]); } } //usage reverseFo...

Cast Object To Interface In TypeScript

Answer : There's no casting in javascript, so you cannot throw if "casting fails". Typescript supports casting but that's only for compilation time, and you can do it like this: const toDo = <IToDoDto> req.body; // or const toDo = req.body as IToDoDto; You can check at runtime if the value is valid and if not throw an error, i.e.: function isToDoDto(obj: any): obj is IToDoDto { return typeof obj.description === "string" && typeof obj.status === "boolean"; } @Post() addToDo(@Response() res, @Request() req) { if (!isToDoDto(req.body)) { throw new Error("invalid request"); } const toDo = req.body as IToDoDto; this.toDoService.addToDo(toDo); return res.status(HttpStatus.CREATED).end(); } Edit As @huyz pointed out, there's no need for the type assertion because isToDoDto is a type guard, so this should be enough: if (!isToDoDto(req.body)) { throw new Error("invalid...

Array Of JSON Object To Java POJO

Image
Answer : This kind of question is very popular and needs general answer. In case you need generate POJO model based on JSON or JSON Schema use www.jsonschema2pojo.org. Example print screen shows how to use it: How to use it: Select target language. Java in your case. Select source. JSON in your case. Select annotation style. This can be tricky because it depends from library you want to use to serialise/deserialise JSON . In case schema is simple do not use annotations ( None option). Select other optional configuration options like Include getters and setters . You can do that in your IDE as well. Select Preview button. In case schema is big download ZIP with generated classes. For your JSON this tool generates: public class Person { private String ownerName; private List <Pet> pets = null; public String getOwnerName() { return ownerName; } public void setOwnerName(String ownerName) { this.ownerName = ownerName; } public List < Pet ...