How to convert an object in vue back into a standard js object? - vue.js

Is there a function to convert objects that have be converted into vuejs's reactive system back into a normal object?

I think you can try:
const normalObject = JSON.parse(JSON.stringify(objectWithReactivity)).

Even try a copy using ecmascript
object_reactive
let object = {...object_reactive}
or maybe just javascript
var obj = { a: 1 };
var copy = Object.assign({}, obj);

Related

Mongoose: Why to convert a received data toObject

I was learning mongoose, and I am trying to figure out.
Why toObject() was needed to convert the data received into Object, when it was already in object form it seems
Here is the code:
UserSchema.methods.toJSON = function() {
var user = this;
var userObject = user.toObject();
return _.pick(userObject, ['_id', 'email']);
};
I cannot understand why toObject() was used to extract the meaningful properties from the object.
Thanks
toObject is a mongoose document method Document.prototype.toObject() which:
Converts this document into a plain javascript object, ready for storage in MongoDB.
You can more about it here
The reason it is called there is because a plain JS object is required in order to do the lodash _.pick which would create a new object with only _id and email properties.

set array of data into mobx array show proxy objects

I'm using react js with mobx and I get data from api.
the data I get is array of objects.
when I set the data into mobx variable then I see array of proxy objects(not sure what the proxy says). I'm trying just to set the array of objects I get from api into mobx variable.
my store
class UserStore {
#persist #observable token = null
#observable tasks = []
#observable done = false
#persist #observable email = ''
constructor() {
}
#action
getTasks = async () => {
try {
let response = await Api.getTasks()
console.log('getTasks',response.tasks)
this.tasks = response.tasks
console.log('my new tasks',this.tasks)
} catch (e) {
console.log(e)
}
}
as you can see here in the first block('black') the data i get from api, then i set the respnse.tasks into this.tasks.
this.tasks = response.tasks
console.log('my new tasks',this.tasks)
You can convert proxy to JS:
import { toJS } from 'mobx'
// example
toJS(response)
It depends on how you want to observe the data.
"I'm trying just to set the array of objects I get from api into mobx variable"
is not really your end-goal.
If you want your observers to:
option a: react when the array reference change
= No care for values in the array.
Use #observable.ref tasks.
option b: react when the references of each value in the array change
= No care for the individual objects properties.
Use #observable.shallow tasks.
option c: react on the individual objects properties too
= Make everything observable, references and object properties
Use #observable tasks like you do.
Like indicated in the comments, mobx5 is using Proxy and some behaviour might differ compared to previous version.
More info: Mobx arrays, Mobx decorators, shallow observability
Note: you would need to give more details if this does not help you, like your react component code.
In my case, toJS was not working because I had a class with a variable with the type of another class. So, I needed to create new objects from the JSON:
parsedArray.map(
(a) =>
new MyObj1({
id: a.id,
myObj2: new MyObj2({
label: a.label,
}),
title: a.title,
})
);
If you run debugger, stop the debugger. It messes the mobx's flow.

Vue - removing all spaces from a string from Firestore database

I am still learning Vue. I know how to remove all spaces from a string using Javascript, such as:
var str = " a b c d e f g ";
var newStr = str.replace(/\s+/g, '');
I can't figure out how to implement this in Vue.
I would like to take a string from my Firestore database, say a field called "title1", with a value of "This is my string" and remove all spaces so it says "Thisismystring". Then I want to be able to use that string in my Vue app in the same way I would use title1... like a variable called title1nospaces.
I'm not sure if I should be using a computed property or a method. Anything I've tried always comes back as "title1nospaces" is not defined on the instance but is referenced during render".
Any help appreciated.
var str = " This is a test ";
var new_str = str.split(' ').join('');
console.log(new_str); // 'Thisisatest'
In your vue app, you should add a mixin and in that mixin you should implement a method that takes an input with spaces and it should return the output as a string without a spaces (or formatted string).
E.g.
let myApp = new Vue({
mixins: [CommonUtils],
});
CommonUtils.js code ( I am using ES6 syntax):
export default {
methods: {
myStringFormattingFun(input) {
// Do your magic and return the formatted string
}
}
}
OR you can just implement the function in your myApp component (main component).

How to get value from then in javascript

i have maybe stupid question.
I m trying to save XML file which i load through xml2js with readfile function.
I want to store file content string to global variable but i dont know how to get from promise then a value.
var myval;
var simpleStore = function(value){
myval = value;
}
var myvariable = RNFS.readFile(APPLICATION_HISTORY_DIRECTORY, 'utf8').then(simpleStore);

HTTPService not properly JSON-encoding nested objects on send()

i am creating an object like this:
var myObj:Object = new Object();
myObj["someProperty"] = {
anotherProperty: "someValue",
whateverProperty: "anotherValue"
}
now i want to send it to a web server (rails):
var service:HTTPService = new HTTPService();
service.url = "http://server.com/some/path/entry.json";
service.method = URLRequestMethod.POST;
service.send( myObj );
the problem is that the server receives the json like this:
{"someProperty"=>"[object Object]"}
is this a problem with HTTPService? should i use the good old loader/urlrequest and serialize myself? by the way, serializing and then passing the string doesn't work, webserver receives empty request as GET.
but i kinda want to use the httpservice class though...
You can use a SerializationFilter with your HTTPService to correctly serialize the data you pass as an object to HTTPService.send().
The way in which this works is to create a custom SerializationFilter to perform the specific action required. In your case, you want to convert the outgoing body Object to a JSON format String. To do this you should override the serializeBody method:
package
{
import mx.rpc.http.AbstractOperation;
import mx.rpc.http.SerializationFilter;
import com.adobe.serialization.json.JSON;
public class JSONSerializationFilter extends SerializationFilter
{
override public function serializeBody(operation:AbstractOperation, obj:Object):Object
{
return JSON.encode(obj);
}
}
}
You can assign an instance of this filter to your HTTPService before calling send():
var service:HTTPService = new HTTPService();
service.url = "http://server.com/some/path/entry.json";
service.method = URLRequestMethod.POST;
//add the serialization filter
service.serializationFilter = new JSONSerializationFilter();
service.send( myObj );
Once assigned, this filter will be invoked for all the operations this HTTPService instance performs. You can also add more override methods to your custom filter to handle the incoming response.
I highly recommend using Mike Chamber's JSON serialization library for encoding / decoding (serializing) data in JSON.
Basically, you need to convert your object into a JSON representation. The JSONEncoder class is useful for this.
There's a useful (old but still very relevant for using HTTPService + JSON) tutorial that goes through it, but essentially you should call JSON.encode() on what your "someProperty" value is.
i.e.:
var dataString:String = JSON.encode(dataValue);
dataString = escape(dataString);
myObj["someProperty"] = dataString;