Browse all properties of a Vuejs object

Asked

Viewed 596 times

2

I am using Vuejs in a project and need to go through all the properties of the object associated with v-model.

I know that if it was an array I could use u for, foreach, map and many other means of traversing it.

But what I need to do is the following: Go through all the properties of an object and make one replace() only in properties that contain /, -, .,(, ), because these characters are from the masks that were used in input's, and do not want to save these characters in the database.

If I were using the mask library as a component I could get the value out without the characters in question, but I am using the mask library as a directive v-mask, and the value that comes from input is always with the mask.

I’ve done a lot of research but haven’t found an efficient method to solve this problem, if anyone can help I appreciate...

Note: It is a requirement of the project that the input are not the v-mask being used as a component because they have been customized and it is a requirement to use them

  • Can you give a more concrete example? or show the code you have to understand better?

  • Let’s say I own the property cep cpfand their respective values are 99000-000 and 123,456,789-10, and they are properties of the same object, as I do to go through the 2 properties and replace the characters . and -, replacing by a '' dynamically, as if it were a function, so that I do not need to do it manually, property by property, even because in the code I am working only one of the objects has 72 properties

  • Forehead obj = Object.keys(obj).reduce((novoObj, key) => ((novoObj[key] = obj[key].replace(/[\.\-]/g, '')), novoObj), {}); that’s what you’re looking for?

  • 1

    That’s exactly it, put it as an answer so I can accept ; )

1 answer

2


You have two options:

  • change the object internally
  • create a new object and overwrite the old one

In your case it makes no difference because the key values are strings. But if they were other objects the first approach could be problematic because it would change objects that could have references in other parts of the code.

In your case you can do so:

obj = Object.keys(obj).reduce((novoObj, key) => {
    novoObj[key] = obj[key].replace(/[\.\-]/g, '');
    return novoObj;
}, {});
  • 1

    I will create a new object and send it to the server. Thank you very much for the help...

  • And what method do I use to check if the property has any of these characters listed above?? match(), includes()??

  • 1

    @Leonardoebert if it is 1 to 1 includes is more practical. Otherwise the match can be both and only need to check 1 time

  • Okay, I’ve been able to implement that

Browser other questions tagged

You are not signed in. Login or sign up in order to post.