I want to create an Object from an array it is possible?
let array = ["name", "Tiger","age", "20"];
I want to make below kind of dynamic object from array. name as a key and Tiger as a value.
let Obj = {name = "Tiger"; age = 20;}
It is possible?
// let arraySize :Nat = array.size() - 1;
// var counter :Nat= 0;
// for (element in array.keys()) {
// if(counter <= arraySize){
// let subArray = Array.subArray<Text>(array, counter,2);
// Debug.print(debug_show(subArray));
// Below is the loop output
// ["name", "Tiger"]
// ["age", "20"]
// };
// counter += 2;
// };
1 Like
I don’t think it’s possible. You can try using JSON instead of motoko objects.
I tried JSON but it is not working. how to Parse JSON.stringify value in motoko?
This seems to be a general issue with the lack of reflection in Motoko right now. The serialization libraries out there also suffer from this where you cant deserialize into a custom type with the exception of from_candid(candidValue)
.
If you know the Obj structure and its static then you can get away with it but anything dynamic seems to be an issue right now. Motoko wishlist - #8 by Gekctek
I find this good. You can make your own functions and facilitate according to requirements
Check out candy library. It has a multi-type array:
https://mops.one/candy
let array = #Array([#Text("name"), #Text("Tiger"),#Text("age"), #Nat("20")]);
//or more likely you want
let map : CandyTypes.CandyShared = #Map([
((#Text("name"),#Text("Tiger")),
((#Text("age"), #Nat(20))
]);
//Cast it to a Candy and you even get look ups:
let map2 = CandyTypes.unshare(map);
let #Nat(age) = Map.get(map2, CandyTypes.candyMapHashTool, #Text("age")) else return #err("anerror");
I tried this it’s give me this kind of Text output.
{"givenName": "John", "familyName": "Doe", "favNumber": 5}
how to convert into motoko object?
hey dynamic motoko objects are not possible at time. So maybe you can switch to use JSON instead.