How to add an element at first of object - javascript

I have an object:
TICKET_PRIORITIES: {
LOW: 'low',
NORMAL: 'normal',
HIGH: 'high',
VERY_HIGH: 'very high'
}
In client side I have to add select at first.
Result I wanted to be
TICKET_PRIORITIES: {
SELECT: 'select',
LOW: 'low',
NORMAL: 'normal',
HIGH: 'high',
VERY_HIGH: 'very high'
}
<select ng-model="selectedPriority" ng-options="key as key | translate for (key, value) in priorities" class="form-control m-b"> </select>
In this select I wanna select "select" option and select option should be at the first of drop down.

var TICKET_PRIORITIES = {
LOW: 'low',
NORMAL: 'normal',
HIGH: 'high',
VERY_HIGH: 'very high'
};
TICKET_PRIORITIES['SELECT']='select';
alert(JSON.stringify(TICKET_PRIORITIES));
Demo

Object properties order are not concerned while creating object but you can create new properties like:
TICKET_PRIORITIES = {
LOW: 'low',
NORMAL: 'normal',
HIGH: 'high',
VERY_HIGH: 'very high'
}
TICKET_PRIORITIES.SELECT='select';

This is not possible. Javascript does not care about or enforce the order of properties in objects (see this question for reference). Or, to quote the ECMAscript standard (emphasis mine):
4.3.3 Object
An object is a member of the type Object. It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.
If order is important to you, you will need a different data structure using arrays, e.g. something like this:
TICKET_PRIORITIES: [
{id: "LOW", label: "low"},
{id: "NORMAL", label: "normal"},
{id: "HIGH", label: "high"},
{id: "VERY_HIGH", label: "very high"}
]
This allows you to do something like this (unshift adds an element to the beginng of an array):
TICKET_PRIORITIES.unshift({id: "SELECT", label: "select"})

Related

Algorithm to disable unnecessary values in an array

to make things clear... I want to explain the basis first.
I have a PRODUCT.
a PRODUCT has different VARIANTS (id, code, price).
VARIANTS have ATTRIBUTES (id, type[select, radio], name).
ATTRIBUTES have VALUES (id, label).
I have a REACT APP to handle variant selecting in product detail (where u add the product into the cart).
It's functioning is this:
All attributes are printed by ID and their selecting html input type is made according to their type (I've specified above).
So... WHAT I WANT TO ACCOMPLISH is THIS.
EXAMPLE:
I have 2 attributes: COLOR, SIZE.
COLOR has 2 values: WHITE, BLACK.
SIZE HAS 3 VALUES: M, L, S.
Product "A" has 2 variants:
#1 VARIANT - COLOR: WHITE; SIZE: M
#2 VARIANT - COLOR: BLACK; SIZE: L,
in a react APP.. I want to filter out ALL options that aren't available to select an existing variant. User CAN NOT select COLOR WHITE; SIZE L variant because it doesn't exist. So, I want to disable the option for him/her.
My REACT STATE structure is the following...
{
"attributes": [
{
"id": 1,
"type": "select",
"name": "size",
"values": [{id: 1, value: "M", selected: true}, {id: 2, value: "L", selected: false}, {id: 3, value: "S", selected: false}],
},
{
"id": 2,
"type": "radio",
"name": "color",
"values": [{id: 1, value: "WHITE", selected: false}, {id: 2, value: "BLACK", selected: false}],
}
],
"variants": [
{
id: 1,
values: [
{
attribute_id: 1,
id: 1
},
{
attribute_id: 2,
id: 1
}
]
},
{
id: 2,
values: [
{
attribute_id: 1,
id: 2
},
{
attribute_id: 2,
id: 2
}
]
}
]
}
so...when I select color WHITE and the size stays unselected... only the option "M" should be displayed. But when I select color BLACK... the size option should be "L" only.
but when NOTHING is selected => EVERYTHING should be visible.
This check should happen EVERYTIME any ATTRIBUTE VALUE Changes. (when I select a SIZE = FILTER OTHER ATTRIBUTES etc...) and it should work dynamically no matter how many attributes are available for a variant.
Any ideas on how to do this please?
THANKS FOR YOUR HELP :)

How to create a threshold in Observable Plot in JavaScript / TypeScript

I am trying to create a grouped bar chart using Observable's Plot.plot in JavaScript (code is in TypeScript).
The problem is that the x-axis is showing each specific date, however I want the dates to show dynamic months or weeks, not specific dates.
This is the code:
const chart = Plot.plot({
x: { axis: null, domain: ["Add", "Remove"], },
y: { tickFormat: "s", label: "↑ Access Requests", grid: true },
color: {
legend: true,
type: "categorical",
domain: ["Add", "Remove"],
range: redGreenColorRange,
},
style: {
background: "transparent",
},
width: 1350,
caption: "in 2 week increments",
facet: {
data: groupedAddRemove,
label: "Created Date",
x: "createdDate",
// thresholds: d3.utcWeeks,
// ^ this doesn't work, but a similar structure has worked in other projects I've seen
},
marks: [
Plot.barY(groupedAddRemove, {
x: "type",
y: "count",
fill: "type",
}),
Plot.ruleY([0]),
],
});
and this is what it looks like:
I want the x-axis marks to show a dynamic version of Months, like:
My data structure either could show the "Date" as a string, or a TypeScript typeof Date object
data structure with date with a type of string
data structure with date with a type of Date
This is the data structure type:
The 'groupedAddRemove' is an array of this type
( AddRemoveBarChartType[] )
type AddRemoveBarChartType = {
createdDate: Date;
count: number;
type: "Add" | "Remove";
};
the "Type" can either be "Add" or "Remove". I had a boolean for this value previously, but the "Add" and "Remove" fit better to automatically have the legend say "Add" and "Remove". It could be changed back to a boolean if there is a better way to display it that way.
The data could be changed in other ways too, if that will simplify things. I am also open to using a D3.js implementation instead of Plot.plot.
I'm very new to Observable Plot.plot so any help is appreciated, thank you!

Is it possible to both select and create the same value in react-select?

I'm trying to have a multi Creatable in which the user can both select a preset value, and "create" the same value by himself, both in the same interaction.
For example, my render look
import CreatableSelect from 'react-select/creatable';
function test(){
render(
<CreatableSelect
isMulti
onChange={this.handleChange}
options = [{ value: 'Blue', label: 'Blue'}, { value: 'Red', label: 'Red'}]
/>
);)
}
I want to let the user both choose 'Blue' as an option, and create the value 'Blue' as well. Namely, I want to output of handleChange to be:
[{ value: 'Blue', label: 'Blue'}, { value: 'Blue', label: 'Blue', __isNew__: true}]
It's not a UI problem for me, as I'm coloring selected values differently based on whether it was created or selected from the list.
Is it possible? I tried having isValidNewOption={() => true} as a prop, but it didn't work.
Found a workaround, which I would not prefer to use if there's a better way:
I can add a special character (or a string) as a prefix to all values (leaving the labels aas is). For example- transforming [{ value: 'Blue', label: 'Blue'}, { value: 'Red', label: 'Red'}]
into [{ value: '$Blue', label: 'Blue'}, { value: '$Red', label: 'Red'}]
Now, it lets my create a new value "Blue", and selecting the value "$Blue". As the label of "$Blue" is still "Blue", the user won't notice the difference.
Lastly, I need to remove the prefix in my onChange function.
It's not a very elegant solution, but better than nothing.

Javascript: Changing DOM elements based on form values

I'm still pretty new to JavaScript programming and I'm having an issue.
JSFiddle: http://jsfiddle.net/Y4pPj/
HTML:
<form id="practiceForm" style="display:inline">
<select id="practiceList" size="1">
<option value="sampleA" selected="selected">Sample A</option>
<option value="sampleB">Sample B</option>
<option value="sampleC">Sample C</option>
</select>
</form>
<button onclick="changeSelection();">Select</button><br />
<span id="currentSelected">Nothing selected</span><br /><br />
Name: <span id="name"></span><br />
Size: <span id="size"></span><br />
Shape: <span id="shape"></span><br />
Value: <span id="value"></span>
JavaScript:
/* var stats = {
sampleA: { name: "Alpha", size: 3, shape: square, value: 1 },
sampleB: { name: "Delta", size: 1, shape: circle, value: 10 },
sampleC: { name: "Gamma", size: 25, shape, triangle, value: 200 }
}; */
function changeSelection() {
document.getElementById("currentSelected").innerHTML = practiceForm.practiceList.options[practiceForm.practiceList.selectedIndex].value;
document.getElementById("name").innerHTML = currentSelected.name;
document.getElementById("size").innerHTML = currentSelected.size;
document.getElementById("shape").innerHTML = currentSelected.shape;
document.getElementById("value").innerHTML = currentSelected.value;
}
What I'm trying to do is, have a combobox list of items with a button. When you click the button, I need to change parts of the HTML to values that I've set in variables at the start.
The code, as it stands, works in JSFiddle. But, as soon as I un-comment the variable declaration, 'stats', it messes up, which really confuses me. Also, please excuse all the undisciplined stuff, like inline styles :) This was just for debugging test.
One more thing while I'm here- is there a way to shorthand the first line in the changeSelection() function? I've seen many examples, but they are all different.
It wont work like this. you need to access the stats through the selected value.
var stats = {
'sampleA': { name: "Alpha", size: 3, shape: 'square', value: 1 },
'sampleB': { name: "Delta", size: 1, shape: 'circle', value: 10 },
'sampleC': { name: "Gamma", size: 25, shape: 'triangle', value: 200 }
};
function changeSelection() {
document.getElementById("currentSelected").innerHTML = practiceForm.practiceList.options[practiceForm.practiceList.selectedIndex].value;
document.getElementById("name").innerHTML = stats[practiceList.value].name;
document.getElementById("size").innerHTML = stats[practiceList.value].size;
document.getElementById("shape").innerHTML = stats[practiceList.value].shape;
document.getElementById("value").innerHTML = stats[practiceList.value].value;
}
look at this fiddle.
http://jsfiddle.net/9QXc4/
It's throwing a syntax error in the console due to your object.
var stats = {
sampleA: { name: "Alpha", size: 3, shape: "square", value: 1 },
sampleB: { name: "Delta", size: 1, shape: "circle", value: 10 },
sampleC: { name: "Gamma", size: 25, shape: "triangle", value: 200 }
};
The above is the correct syntax. Things needed fixing:
-Quote property values! square, circle, and triangle were unquoted.
-The "shape" property had a comma rather than a colon to declare the value
Use the console when programming, you'll see this error right away:
Uncaught SyntaxError: Unexpected token ,
Which was caused by:
sampleC: { name: "Gamma", size: 25, shape, "triangle", value: 200 }
^^
Just replace sampleC: { name: "Gamma", size: 25, shape, triangle, value: 200 } with this sampleC: { name: "Gamma", size: 25, shape: triangle, value: 200 }
You put a comma instead of a colon

Select Records with Unique Combinations of Fields in Meteor.js

In Meteor.js, how can we select unique combination of fields? For example, if we have:
type color owner
---- ----- -----
animal red paul
animal red jack
animal blue paul
food blue jack
what should be done to get the following result set:
type color
---- -----
animal red
animal blue
food blue
I'm using meteor-smart-collections 0.4.0 and Meteor 0.7.0.1
You can use underscore to do this fairly easily if you're prepared to do a fetch(), which probably depends on how many documents you've got:
_.uniq(yourCollection.find({}, {fields: {type: 1, color: 1, _id: 0}}).fetch(), function(item) { return item.type+item.color; });
The only word of warning is that you're concatenating strings for the purposes of comparison, so it would fail if there was any possibility of pairs like {type: 'foo', color: 'bar'} and {type: 'foob', color: 'ar'}. This doesn't seem to be likely in the example you give, but if you're concerned about it being a problem you would just need to change the structure of the iterator function to do something a bit more imaginative than concatenating the two fields. It needs to return a primitive though, I don't think it'll work if you return an object or an array.
I don't think Meteor's Minimongo driver includes a helper for the Aggregation Framework yet, however there are suggestions on how to call the underlying MongoDB aggregate command on at least one of the issues.
Assuming your data looks like:
db.things.insert([
{ type: 'animal', color: 'red', owner: 'paul'},
{ type: 'animal', color: 'red', owner: 'jack'},
{ type: 'animal', color: 'blue', owner: 'paul'},
{ type: 'food', color: 'blue', owner: 'jack'}
])
You can do this grouping on the server side using MongoDB's Aggregation Framework and the $group operator:
db.things.aggregate(
{ $group: {
_id: { type: "$type", color: "$color" }
}}
)
The results would look like:
{
"result" : [
{
"_id" : {
"type" : "food",
"color" : "blue"
}
},
{
"_id" : {
"type" : "animal",
"color" : "blue"
}
},
{
"_id" : {
"type" : "animal",
"color" : "red"
}
}
],
"ok" : 1
}

Categories