Is there a way to tell the stringify method to convert an object to a primitive datatype?
class Bar {
constructor() {
this.name = 'bar';
}
}
const obj = {foo: new Bar};
JSON.stringify(obj);
// output: '{foo: {name: 'bar'}}'
// wanted output: '{foo:'bar'}'
I've tried overriding toSting and valueOf methods but with no results
Bar.prototype.toString = function() {
return this.name;
}
Bar.prototype.valueOf = function() {
return this.name;
}
Add toJSON prototype method in Bar class.
Bar.prototype.toJSON = function() {
return this.name;
}
Related
i'm try to make Search Bar and Searching from Map<String, List>
but i got error like this --> "A value of type 'Iterable<MapEntry<String, List>>'
can't be assigned to a variable of type 'Map<String, List>"
//here the function that i try.
Map<String, List> datasource_map = {};
Map<String, List> result = {};
void updateList(String enteredKeyword) {
setState(() {
result = datasource_map.entries.map((e) {
return MapEntry(
e.key,
e.value
.where(
(element) => element.foodName!.toLowerCase().contains(
enteredKeyword.toLowerCase(),
),
)
.toList());
});
print("### $result");
});
}
this is my Model of foodCard
what should i try ? i am new at flutter
Looks like your datasource_map.entries is a List - calling a map() on it will produce an Iterator - not a Map object.
You should use Map.fromEntries constructor:
result = Map.fromEntries(datasource_map.entries.map((e) {
return MapEntry(
e.key,
e.value
.where(
(element) => element.foodName!.toLowerCase().contains(
enteredKeyword.toLowerCase(),
),
)
.toList());
}));
Thank you everyone! I solved it.
This works:
Map<String, List<dynamic>> result = {};
void updateList(String enteredKeyword) {
Map<String, List<dynamic>> mapResult = {};
datasource_map.forEach((key, value) {
List foodByFilter = value.where((element) {
return element.foodName
.toLowerCase()
.contains(_textEditingController.text.toLowerCase().toString());
}).toList();
if (foodByFilter.isNotEmpty) mapResult[key] = foodByFilter;
});
setState(() {
result = mapResult;
});
}
Please take into account that this question is about Typescript and not vanilla Javascript.
I am trying to deserialize a very simple JSON string into a Typescript object and then casting into the correct type.
After casting at const obj = <FooClass>JSON.parse(s) I would expect the typeof operator to return FooClass. Why the operator still returns object ?
Why does casting here fails? How can I deserialize and still have access to somefunc ?
Example code:
class FooClass {
public baz = 0
public somefunc() {
return this.baz * 2
}
}
const jsonData = {
baz: 1234,
}
test('deserialize example', () => {
const s = JSON.stringify(jsonData)
const obj = <FooClass>JSON.parse(s) // Cast here
console.log(typeof obj) // typeof still returns object
console.log(obj)
console.log(obj.somefunc())
})
Output:
console.log
object
at Object.<anonymous> (tests/deserialize.test.ts:15:11)
console.log
{ baz: 1234 }
at Object.<anonymous> (tests/deserialize.test.ts:17:11)
TypeError: obj.somefunc is not a function
In typescript you can cast any (return type of JSON.parse) to anything. The responsibility of ensuring if the casting is "correct", and the casted value indeed matches the type it's being casted to is yours.
Casting is only telling the type checker how to treat that value from the point of casting.
Turning that object to an instance of your class is also your responsibility. You could however do something like this:
type Foo = {
baz: number
}
class FooClass {
public baz: number = 0
constructor(input: Foo) {
this.baz = input.baz
}
public somefunc() {
return this.baz * 2
}
}
const rawFoo = JSON.parse(s) as Foo
const fooClassInstance = new FooClass(rawFoo)
// ready to be used as an instance of FooClass
Playground
For completion, I copy here a solution that I find both efficient and clean:
test('casting fails example', () => {
const s = JSON.stringify(jsonData)
const obj = Object.assign(new FooClass(), JSON.parse(s))
console.log(typeof obj)
console.log(obj)
console.log(obj.somefunc())
})
This could later be improved using generics
function deserializeJSON<T>(c: { new (): T }, s: string): T {
return Object.assign(new c(), JSON.parse(s))
}
const obj = deserializeJSON(FooClass, s)
In my states I have categories. In the categories array every each category have a settings column where I have saved json array string.
My question it is,how can I turn my string to object by filtering the response ?
My response:
[{"id":4,"name":"Vehicles","slug":"vehicles","settings":"[{"edit":true,"searchable":true}]","created_at":"2019-01-26 16:37:36","updated_at":"2019-01-26 16:37:36"},
This is my loading action for the categories:
const loadCategories = async ({ commit }, payload) => {
commit('SET_LOADING', true);
try {
const response = await axios.get(`admin/store/categories?page=${payload.page}`);
const checkErrors = checkResponse(response);
if (checkErrors) {
commit('SET_DIALOG_MESSAGE', checkErrors.message, { root: true });
} else {
commit('SET_STORE_CATEGORIES', response.data);
}
} catch (e) {
commit('SET_DIALOG_MESSAGE', 'errors.generic_error', { root: true });
} finally {
commit('SET_LOADING', false);
}
};
This is my SET_STORE_CATEGORIES:
const SET_STORE_CATEGORIES = (state, payload) => {
state.categories=payload.data;
state.pagination = {
currentPage: payload.current_page,
perPage: payload.per_page,
totalCategories: payload.total,
totalPages: payload.last_page,
};
};
Here I would like to add to modify the value ,to turn the string to object.
Had to add:
let parsed=[];
parsed=response.data.data.map((item)=>{
console.log(item);
let tmp=item;
tmp.settings=JSON.parse(item.settings);
return tmp;
});
response.data.data=parsed;
commit('SET_STORE_CATEGORIES', response.data);
You could map your response data as follows by parsing that string to an object :
let parsed=[];
parsed=response.data.map((item)=>{
let tmp=item;
tmp.settings=JSON.parse(item.settings);
return tmp;
});
commit('SET_STORE_CATEGORIES', parsed);
I want to implement indexer to get elements from data property with index as JavaScript arrays. I heard about ES6 proxies but I couldn't implement it to my class. Is it possible now or should I wait more to come with ES7.
class Polygon {
constructor() {
this.data = new Set(arguments)
}
[Symbol.iterator](){
return this.data[Symbol.iterator]()
}
add(vertex){
this.data.add(vertex)
}
remove(vertex){
this.data.delete(vertex)
}
get perimeter(){
}
get area(){
}
}
let poly = new Polygon()
let first_vertex = poly[0]
AFAIK there is no proposal for something like "indexing" into arbitrary objects, so yes, you would have to go with proxies.
I couldn't really test this since no environment seems to support both classes and proxies, but in theory, you'd have to return the new proxied object from the constructor. Tested in Chrome v52.
Example:
class Test {
constructor(data) {
let self = this;
this.data = data;
this.foo = 'bar';
return new Proxy(this, {
get(target, prop) {
if (Number(prop) == prop && !(prop in target)) {
return self.data[prop];
}
return target[prop];
}
});
}
}
var test = new Test([1,2,3]);
console.log(test[0]); // should log 1
console.log(test.foo); // should log 'bar'
I want to have a variable in a TypeScript class that is of the type "boolean isVisible()".
How do I declare it?
How do I assign this function for another instantiated object to this variable?
How do I call this function?
ps - This seems so basic but 10 minutes of searching and I couldn't find it.
function boolfn() { return true; }
function strfn() { return 'hello world'; }
var x: () => boolean;
x = strfn; // Not OK
x = boolfn; // OK
var y = x(); // y: boolean
Here's one way of doing it, though I'll be happy to work with you to figure out exactly what you're trying to achieve.
export module Sayings {
export class Greeter {
isVisible(): boolean {
return true;
}
}
}
var greeter = new Sayings.Greeter();
var visible = greeter.isVisible();
You could also use a property instead of a function. Your original question talks about a "variable" and a "function" as if they're the same thing, but that's not necessarily the case.
export module Sayings {
export class Greeter {
isVisible: boolean = false;
}
}
var greeter = new Sayings.Greeter();
var visible = greeter.isVisible;
greeter.isVisible = true;
Or something like this maybe?
export module Sayings {
export class Greeter {
constructor(public isVisible: () => boolean) {
}
}
}
var someFunc = () => {
return false;
}
var greeter = new Sayings.Greeter(someFunc);
var visible = greeter.isVisible();