Add node when data exists Javascript - javascript

Hello everybody I am working with a LWC form. In my .js I create a json wrapper to pass the user inputed information to an Apex controller to validate each one of the data. Such as this:
`cliente:{
IdCliente:{
identificatorType: this.identificatorType,
identificator: this.identificator,
personType: this.tipoPerson
.......
},`
Of course not all the lightning-inputs are required. The problem comes when the the user dont need to inform that input. In my console.log I could see that the node appears with ("") when the user dont input nothing(because I coded it) like this:
`personType;
handlePersonType(event){
this.personType = event.target.value;
if(this.IdentificatorType !== 'NV' || this.IdentificatorType !== 'OT'){
this.personType = ''
}
}
`
When the user inputs the data but for example the personType, which is not required, it informs with the ''. But what I need to do is when the personType has any value different to the null/'' to add this info in the json wrapper. For example if the user inputs something I want this:
"Client": { "IdClient": { "IdentificatorType": "OT", "Identificator": "98720437601374", "PersonType": "Person A" },
And when the user dont input nothing in the PersonType node. To look like this:
"Client": { "IdClient": { "IdentificatorType": "OT", "Identificator": "98720437601374", },
I mean without the node. Could anybody help me? And write some example?

Related

couchdb views: return all fields in doc as map

I have a doc in couchDB:
{
"id":"avc",
"type":"Property",
"username":"user1",
"password":"password1",
"server":"localhost"
}
I want to write a view that returns a map of all these fields.
The map should look like this: [{"username","user1"},{"password","password1"},{"server","localhost"}]
Here's pseudocode of what I want -
HashMap<String,String> getProperties()
{
HashMap<String,String> propMap;
if (doc.type == 'Property')
{
//read all fields in doc one by one
//get value and add field/value to the map
}
return propMap;
}
I am not sure how to do the portion that I have commented above. Please help.
Note: right now, I want to add username, password and server fields and their values in the map. However, I might keep adding more later on. I want to make sure what I do is extensible.
I considered writing a separate view function for each field. Ex: emit("username",doc.username).
But this may not be the best way to do this. Also needs updates every time I add a new field.
First of all, you have to know:
In CouchDB, you'll index documents inside a view with a key-value pair. So if you index the property username and server, you'll have the following view:
[
{"key": "user1", "value": null},
{"key": "localhost", "value": null}
]
Whenever you edit a view, it invalidates the index so Couch has to rebuild the index. If you were to add new fields to that view, that's something you have to take into account.
If you want to query multiple fields in the same query, all those fields must be in the same view. If it's not a requirement, then you could easily build an index for every field you want.
If you want to index multiple fields in the same view, you could do something like this:
// We define a map function as a function which take a single parameter: The document to index.
(doc) => {
// We iterate over a list of fields to index
["username", "password", "server"].forEach((key, value) => {
// If the document has the field to index, we index it.
if (doc.hasOwnProperty(key)) {
// map(key,value) is the function you call to index your document.
// You don't need to pass a value as you'll be able to get the macthing document by using include_docs=true
map(doc[key], null);
}
});
};
Also, note that Apache Lucene allows to make full-text search and might fit better your needs.

How to create append an array to a json value using (js/node/express)

I'm trying to re-create a CRUD app in NodeJs that I did using php/mysql etc, that takes a users form information and stores it in a file called "sample-data.json".
Essentially, with NodeJs a user fills in a form, front-end JS takes that info, passes it along to an api route I set up, and then using FS, writes that info to the sample-data.json file etc.
With the code below, once a users hits submit on the form, the code takes that info, and passes it to the "sampledataapi" route.
$("#createTodoForm").submit(function(evt){
evt.preventDefault();
$.post("/sampledataapi",{
todoCompany : $("#todoTitle").val(),
thisTodoIsFor : $("#todoIsFor").val(),
todoPostedBy : $("#todoPostedBy").val(),
todoCompleted : $("#todoCompleted").val(),
todoPriority : $("#todoPriority").val(),
todoMessages : $("#todoFirstMessage").val()
}, showDataGotten );
});
Once it saves the data, my sample-data.json file which initially has an empty array inside of it, then gets populated with info.
So sample-data.json goes from this: []
To this(once data has been entered):
[
{
"todoCompany":"sample company",
"thisTodoIsFor":"todo is for me",
"todoPostedBy":"admin",
"todoCompleted":"no",
"todoPriority":"green",
"todoMessages" : "sample message"
}
]
Now when I do this, all works fine but I run into problems when I want to have "todoMessages" be an array from the get go. Reason is that once the user posts their data, they will have the ability to erase/add messages from that block.
So I need that when the user submits the data, instead of that "todoMessages" being a regular string, I want it to be like this:
"todoMessages" : [ "sample message" ]
This way, I can push info into it OR delete from it etc.
How can I make it so that when the user creates his data, and the data passes the info to the route/json file, that it automatically creates todoMessages as an array?
I have tried (on front end)
todoMessages : [$("#todoFirstMessage").val()]
but then the front end reads "undefined"
and the backend json has this:
"todoMessages[]":"sample message"

How can I change the value in a nested array of objects, after a button click using JQuery and javascript?

I'm trying to make a voting app using Node.js, Javascript, JQuery, Jade and a json file for practice.
In short, I'm trying to count the votes for each option to eventually render it into a chart. Specifically I was trying to add + 1 to the object value {"value": 0} in the json each time someone chooses a radio button correlated to the option and hits submit. I can get to the e.g. {"option": "Puppies","value": 0} in my JQuery and I've been trying to find a way to change the object value within the $("#btnVote").click(function(){}). I'm not sure if that would be possible or the best way.
Here is a sample of the JSON database.
[{
"name": "Puppies or Kitties",
"id": "f2754172-1c58-41ed-ae84-74e046888adb",
"choices" : [{"option": "Puppies","value": 0}, {"option": "Kittens","value": 0}],
"admin": true}]
Here is the Jade I am using to dynamically render the poll options.
form(method="post")
fieldset.form-group
h1 #{poll.name}
form
table
each choice in poll.choices
tr
td=choice.option
input(type='radio',value=choice.value id=choice.option name="Answer" class="clsAnswer", style='margin:10px')
br
input(type="button", value="Submit Vote", id="btnVote")
A visual if it helps
Here is the JQuery I've used so far;
//Radio button vote function
$("#btnVote").click(function () {
var selected = $(".clsAnswer:checked");
if (!selected.val()) {
alert("No Choice Was Made!");
}
else {
var optionName = $('input[type=radio][name=Answer]:checked').attr('id');
var selectedValue = selected.val();
selectedValue = parseInt(selectedValue);
alert("Value: " + selectedValue + " " + optionName);
};
});
Thank you all in advance!
There are two ways that you can change the object value in this case, either through your JSON being in a database such as mongodb or through cookies as a temporary change.
The current JQuery is set up to receive the static html and not from the JSON file.
Since the JSON file is used as practice in the folder hierarchy and static (as well as the html), this current setup will not render updating the object value in JSON or even as a temporary change as you would maybe see in cookies.
One other alternative would be to use node.js and create a new JSON file but that is not what is being aimed at in this application.

pass Algolia id attribute instead of Name Atributre in a post request on Laravel 5.2

Using the Javascript, Vue.js and Typeahead.js way shown by Jeffery Way and Algolia docs to index json objects from the Algolia platform.
Currently when i search for the result i require and hit the submit button, It is passing the name attribute through in the post request.
How is it possible to pass the name and the id attribute or if nescessery just the ID arrtibute would work.
<script>
new Vue({
el: 'body',
data: {
query: '',
users: []
},
ready: function(){
this.client = algoliasearch("MYID", "MYAPI");
this.index = this.client.initIndex('dev_category_list');
$('#typeahead').typeahead(null, {
source: this.index.ttAdapter(),
displayKey: 'name'
});
},
methods: {
search: function(){
if (this.query.length < 3) return;
this.index.search(this.query, function(error, results){
this.users = results.hits;
}.bind(this));
}
}
})
</script>
As a total newcomer the laravel, vuejs and javascript its somewhat difficult to get to grips with the syntax and phrases used when explaining the instructons within the docs so any help would be greatly appreciated.
My indexed objects look like so:
{
"id": "3",
"name": "My Product 3",
"value": "3",
"alternative_name": "Prod 3",
"objectID": "3"
}
Im hoping to pass the value of ID or objectID along with the name attribute in a post request once the user selects the given result from the algolia drop down menu and hits the submit, just the ID would work as mentioned above if its not possible.
Thanks.
--- Update referencing Jerska: ---
Ok so after playing around as a newbie for a little bit i seem to have it working, Im not exactly sure how secure this is or how reliable one would say, Hopefully im not a million miles off from where i need to be. Be good to see what your personal and professional thoughts are.
.on('typeahead:select', function (e, suggestion) {
$('#typeahead').change(function() {
var val = suggestion.id;
$('#st').val(val);
});
I have created a hidden input field and named is 'st' for a demo and on update of the algolia results jquery is using the .change function to append the value to the hidden input fields value. That way the form can be continued and sibmitted as i originally wanted and hoped for, The benefit here is that even if the user is to select a result from algoia drop down menu then continue with the form, If he or she decides they want to go back to the search field and change it, They can do before they submit the form or before any window.location is run, I even thought of using ajax or simply jquery $.post but its working ok the .change
Look forward to hearing your thoughts.
Thanks
If you want to redirect to an item page, the typeahead:select event gives you the selected option :
$('#your-input')
.typeahead(/* ... */)
.on('typeahead:select', function (e, suggestion) {
window.location = suggestion.url;
});
from Algolia redirect to search results
You can access the selected object through the suggestion parameter. You could definitely use something like
window.location = 'YOUR_URL?id=' + suggestion.id + '&name=' + suggestion.name;
This assumes you're using typeahead.js#0.11.
typeahead.js being unmaintained, Algolia recommends to use their own fork of typeahead.js#0.10, autocomplete.js.
Here are the different event names and handlers signatures depending on what library/version you're using:
typeahead.js#0.11: typeahead:select -> function($event, suggestion)
typeahead.js#0.10: typeahead:selected -> function($event, suggestion, datasetName)
autocomplete.js: autocomplete:selected -> function($event, suggestion, datasetName)

Backbone Model get attribute function returns last updated value

If there's an optional field in the server returned JSON top structure. Backbone Model seem to cache previously set value. Lets say i get a JSON like this
{
label: "test_label",
attr1: "test1",
attr2: "test2"
}
when I say #model.get("label") i get "test_label". So later on, if i get a JSON like this
{
attr1: "test1",
attr2: "test2"
}
i get "test_label" when i query for #model.get("label"). Is this a known issue in backbone.js? I do something like this to fetch
#modelXhr = #model.fetch
success: (-> this.trigger('reset')).bind #model
I'm a beginner in javascript/coffeescript, What can i do so when i query for a field which doesn't exist in the latest returned model I won't get an older value? Appreciate your help
You should either clear the model beforehand using #model.clear() or (in my opinion the better way) ensure that the data format for a specific model type does not change. Return { label: null, ... }
You are then later on able to check for the existence of the label using #model.get("label")?
If you are not able to ensure data integrity throughout your requests, clear the model.

Categories

Resources