Equivalent to `.push()` for object instead of array - object

I originally had an array of data with sub-arrays, however I need to make this an object instead.
My final data should look something like:
var invalidFields = {
0: {
lastName: <input type="text" ... />,
city: <input type="text" ... />,
...
}
2: {
lastName: <input type="text" ... />,
city: <input type="text" ... />,
...
}
}
Please note, above, that there is no key 1.
I am having trouble adding the data to the object. I am iterating over an existing array and finding matches that are invalid, and then want to "push" them to a new object.
For example the key for the top-level multi-dimension e.g 0 or 2 is stored as passengerIndex in my code but I cannot work out how to add it.
I am initialising with invalidFields = {}
I have tried. invalidFields[passengerIndex]
I have also tried invalidFields.passengerIndex
And invalidFields = invalidFields[passengerIndex]
But none work.

Assuming you are working with Javascript
You will need to find another variable-name, maybe add an underscore before the number since a variable cannot start with a number
see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types
A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($)
or maybe you could use a Map https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

Related

Convert JSON String to Object nodejs

products.json: {"model": "PLM-7-P-21","category":["classic","new"],"fabric":["white","beech","glass"], "shine": "false","size": "45x25","bulb": 2, "id": "5cfa55c5"},`
and then I want to use category and fabric as data-category:const layout = require('../layout');module.exports = ({ products }) => {const renderedProducts = products.map(product => {return <div class="image shopProduct" data-category=${product.category}><img src="data:image/png;base64, ${product.image}"/><h3 class="subtitle">${product.title} ${product.model}</h3><h5>${product.price} zł</h5><form action="/cart/products" method="POST"><input hidden value="${product.id}" name="productId" /><button class="button has-icon is-inverted">Dodaj do<i class="fa fa-shopping-cart"></i></button></form></div>;}).join('\n');`
but then I have got a string data-category="classic, new" but I want to get data-category="classic new" without comma...
I would be grateful for your help.
I think you are looking for JSON.parse which will convert string data directly to a JSON object, so long as the string is in valid syntax.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
Instead of
data-category=${product.category}
do
data-category=${product.category.join(' ')}
You are getting the comma because the default serialization of an array separates elements with a comma.

How to reference data from vue,js pug template?

Basically I am trying to make a permalink from an event name. When I get the value from the event name using v-model it works but how do I put the converted permalink back in another input box in pug?
This works:
"P {{message}}",textarea(rows="2") {{message}}
but when i try the following:
input(value="{{message}}"),input(value={{message}}),input(value=#{{message}}),input(value=#{{message}}),input(value=#{message})
Pug does not render it & shows an indent error.
My question is how do I bind or reference data from Vue in input values ?
Pug template:
.col-md-12(style="padding:0px;")
.col-md-2.labelcont
label.labeltext Event Name :
.col-md-10
input(
type="text"
class="form-control"
placeholder="Event Name"
v-model="eventname"
)
.col-md-12(style="padding:0px;")
.col-md-2.labelcont
label.labeltext Permalink :
.col-md-10
textarea(
type="text"
class="form-control"
placeholder="Event Permalink"
) {{eventpermalink}}
Vue.js code:
var basicinfo = new Vue({
el: '#basic',
data: {
eventname: '',
eventpermalink: '',
}
})
basicinfo.$watch('eventname', function (newValue, oldValue) {
basicinfo.eventpermalink = basicinfo.eventname.replace(/[^a-zA-Z0-9 ]/g,'').replace(/ +/g,'-').toLowerCase();
})
You can use the v-bind directive. This way, you can bind any HTML element's attribute to a value whether it's calculated or a reference to your props or data.
In your case, it would be something like this:
input(type="text" class="form-control" placeholder="Event Name"
v-model="eventname" v-bind:value="YOUR-DATA-OR-WHATEVER")
Look the official documentation for further reading:
https://v2.vuejs.org/v2/guide/syntax.html

Angular 2 weird template scope behavior

Just went through the Tour of Heroes tutorial app and experienced some interesting behavior within my template. I started the second part of the tutorial with the following code:
class Hero {
id: number;
name: string;
}
#Component({
selector: 'my-app',
template:`
<h1>{{title}}</h1>
<h2>{{hero.name}} details!</h2>
<div><label>id: </label>{{hero.id}}</div>
<div>
<label>name: </label>
<div><input [(ng-model)]="hero.name" placeholder="name"></div>
</div>
`,
directives: [FORM_DIRECTIVES]
})
class AppComponent {
public title = 'Tour of Heroes';
public hero: Hero = {
id: 1,
name: 'Windstorm'
};
}
When instructed to add the array of new heroes (var HEROES: Hero[] = [ /* Hero Data */];) and the new property to my component, I assumed we were replacing the original hero property and ended up with this:
class AppComponent {
public title = 'Tour of Heroes';
public heroes = HEROES;
}
Next, the template was modified like so:
<h1>{{title}}</h1>
<ul class="heroes">
<li *ng-for="#hero of heroes">
<span class="badge">{{hero.id}}</span> {{hero.name}}
</li>
</ul>
<h2>{{hero.name}} details!</h2>
<div><label>id: </label>{{hero.id}}</div>
<div>
<label>name: </label>
<div><input [(ng-model)]="hero.name" placeholder="name"></div>
</div>
In the browser, the unordered list then rendered one li per hero in the array, but did not print the name or id. Crazy. After some tinkering, I realized that if I added the original hero property back to the AppComponent class all of the heroes in the array rendered just fine. Also, if I simply removed any template code referencing the hero property not in the ng-for loop the list would also render just fine.
Here is what I expected:
In my original version, all of the heroes in the array should be reflected in the unordered list, but then all of the hero values outside of the loop should be undefined or possibly the last item in the list.
When I added back the original hero property, there should be some sort of name collision or some other side effect.
How does this work the way it does?
Edit: Here is the requested plunker: http://plnkr.co/edit/U3bSCaIOOjFdtw9XxvdR?p=preview
Ok so with your plunker I got a bit more of what you were trying to do and the issues you were having.
My Working plunk with more details is HERE
1. NG-For
When you do a NG-For loop the "#" variable is isolated to be inside the loop only. I renamed it "domhero" so you can see.
You had a few calls to it OUTSIDE of the li object which wouldn't work. I re-wrote it a bit to put all your titles and stuff inside the LI loop.
2. Variables from the object
On the input you were trying to access a variable from inside the ng-for loop which you cant do. Once you close out of a loop you cant access those variables. So I showed where I was binding to, to make it clearer for you.
I think it got confusing when you had so many things named the same thing all over the place (hero, heroes, HEROES, class: hero) if you take a look at the plunker I made I renamed the variables to help mark where they are coming from.
Hope it helps!
p

How does one parse nested elements using express.bodyParser/node-formidable?

I'm using express.js with the bodyParser middleware (which, is technically node-formidable, behind the scenes).
I'd like to take and create a form that represents inputs for each of the data elements listed here:
{
"name" : "asdf",
"children" : [
{
"child_name" : "xyz1234",
"size" : 12
},
{
"child_name" : "1234aszds"
"size": 14
}
]
}
The number of children here will be dynamic, but I'd like to be able to add additional fields client-side, and have them map into req.body on the server.
Note, I'm looking for how to name the inputs in the client in order for the raw POST body to have the correct encoding to allow node-formidable to parse them out into an array.
The general way to achieve this is as follows (excluding non-essential attributes for clarity):
<input name="name"/>
<input name="children[0[child_name]"/>
<input name="children[0[size]"/>
<input name="children[1[child_name]"/>
<input name="children[1[size]"/>
Note that the square brackets are not balanced, this is required due to a "bug" in the "querystring" package (or, at least it would seem so, as of August 20th, 2013).
But, if the square brackets are left unbalanced, as above, the result is that this will be parsed into the object structure requested in my original question (i.e. this will be made available as "req.body").
The benefit of this is that it does not require any Javascript to do any "pre-flighting" on form submission.
Using an HTML form with input fields will be problematic since there is no easy way to define the structure without parsing each field name to determine its place in the structure.
For instance, if you posted the following:
<form action="/post" method="post">
<input type="text" name="data[name]">
<input type="text" name="data[children][][child_name]">
<input type="text" name="data[children][][size]">
<input type="text" name="data[children][][child_name]">
<input type="text" name="data[children][][size]">
<input type="submit" value="Submit">
</form>
Formidable would interpret into this JSON structure:
[ [ 'data[name]', 'name' ],
[ 'data[children][][child_name]', [ 'cname1', 'cname2' ] ],
[ 'data[children][][size]', [ 'csize1', 'csize2' ] ] ]
To post deep structures this way, I would recommend using AJAX and posting a complete JSON object instead, which I have outlined below.
The following should allow you to copy all of the fields directly into req.body. I elected to use the .mixin() helper from the utile library.
var utile = require('utile')
var form = new formidable.IncomingForm()
, fields = {}
form
.on('field', function (field, value) {
fields[field] = value
})
.on('end', function () {
req.body = utile.mixin(req.body, fields)
})
Based on your JSON in the question itself, you could then access your values like this:
console.log(req.body.children[0].child_name)
If you are looking for a native way of merging the objects, see Combine or merge JSON on node.js without jQuery for a way to do this.
Hopefully this answers the question and helps you out!

text box value to a javascript variable instantly after change

i want to type a numerical value in a text box and after i type it i want it to be assigned to a JavaScript variable instantly without submitting it
so the idea is
type a number
var x = that number instantly
Here is the html
<form id="tools">
<input type="text" id"stk"/>
</form>
now what is the javascript? :D
you can achive that assigning an a handler for the event (onKeyUp)... and that handler should assign the value to the variable. I suggest you to use jQuery instead of pure javascript.
With jQuery should look like this:
var x = 0;
$('#textbox-name').onkeypress(function({
x = $(this).attr('value');
}));
Sorry if I made a mistake with the syntax, but that's the main idea.
Your Jsp :
<form action="someAction" method="post">
<input type="text" name="text" id="text" />
<input type="text" name="value" id="value" />
</form>
Java Script needed is :
var myVar=setInterval(function(){getValue()},5000);
function getValue()
{
document.getElementById("value").value=document.getElementById("text").value;
}
By this type of JavaScript function the value of the text field will be received by JavaScript for every 5 Seconds . If you need instantly you can replace 5000 with 0. I think its little bit clumsy try to understand it

Resources