Alter value in object - javascript

Writing Javascript, I have an object/class with the following attributes:
this.option1Active = null;
this.option2Active = null;
this.option3Active = null;
this.option4Active = null;
I would like to set one of those attributes to true based on the parameter genre
function selectGenre (genre) {
if (genre === 'option1') {
this.option1Active = true;
}
else if (genre === 'option2') {
this.option2Active = true;
}
else if (genre === 'option3') {
this.option3Active = true;
}
else if (genre === 'option4') {
this.option4Active = true;
}
}
Though writing if statements is not a sustainable solution.
I'd like to do something like this:
function selectGenre (genre) {
var options = {
'option1': this.option1Active,
'option2': this.option2Active,
'option3': this.option3Active,
'option4': this.option4Active
};
options[genre] = true;
}
But that only set options[index] to true, not e.g. this.option1Active.
Is there a way to change the reference a key of an object points to?
If not, other ways of refactoring the if statements is greatly appreciated.

You can use a string for the property name to set on this.
var genreOptions = {
'option1': 'option1Active',
'option2': 'option2Active',
'option3': 'option3Active',
'option4': 'option4Active'
};
function selectGenre (genre) {
this[genreOptions[genre]] = true;
}

It seems you can just append "Active" to genre to get the property itself:
function selectGenre (genre)
{
var prop = genre + 'Active';
if (typeof this[prop] != 'undefined') {
this[prop] = true;
}
}
Though, it would be easier if you could use an array as your property instead, i.e. this.optionActive[3] vs. this.option3Active.

Is this what you want ?
var obj = {};
obj.option1Active = null;
obj.option2Active = null;
obj.option3Active = null;
obj.option4Active = null;
var options = {
option1: 'option1Active',
option2: 'option2Active',
option3: 'option3Active',
option4: 'option4Active'
};
function selectGenre(genre) {
obj[options[genre]] = true;
}
console.log(obj);
selectGenre('option2');
console.log(obj);

Related

How fix warning "Expected to return a value in arrow function array-callback-return"

This is my code:
form.listPrice.map(list => {
if (list.id === listId) {
form.active = true
listPrice = parseInt(list.price)
if (list.offerPrice) {
listofferPrice = parseInt(list.offerPrice)
} else {
listofferPrice = null
}
}
})
And here:
n.listPrice.map(list => {
if (list.id === listPrice) {
valid = true;
n.active = true;
n.showPrice.price = list.price;
n.showPrice.offerPrice = list.offerPrice;
n.ladder = list.ladder;
}
And this output the same warning:
Expected to return a value in arrow function array-callback-return
You are using .map incorrectly. .map should be used only when you want to construct a new array from an old array, but your code is not doing that - you're only carrying out side-effects - the setting of form.active and listofferPrice.
The first step would be to use forEach or for..of instead, eg:
for (const list of form.listPrice) {
if (list.id === listId) {
form.active = true
listPrice = parseInt(list.price)
if (list.offerPrice) {
listofferPrice = parseInt(list.offerPrice)
} else {
listofferPrice = null
}
}
}
But since it looks like you're trying to find a possible single matching value in the array, .find would be more appropriate:
const found = form.listPrice.find(list => list.id === listId);
if (found) {
form.active = true
listPrice = parseInt(found.price)
if (found.offerPrice) {
listofferPrice = parseInt(found.offerPrice)
} else {
listofferPrice = null
}
}
const found = n.listPrice.find(list => list.id === listPrice);
if (found) {
valid = true;
n.active = true;
n.showPrice.price = found.price;
n.showPrice.offerPrice = found.offerPrice;
n.ladder = found.ladder;
}

value is not added to multidimensional array

The first time the function fires I get this result:
output1:test
The output2 2 alert is not firing. I know something is probably undefined in alert Does anyone know why the value won't be added in the multidimensional array?
I expect this to display after the false1:
output2:test2
Also if you want to fiddle with the code here it is:
https://jsfiddle.net/ndf0sjgf/1/
var carSelectedArray = [
[null]
];
addRow(carSelectedArray);
addRow(carSelectedArray);
function addRow(carSelectedArray) {
var arrayempty = false;
if (carSelectedArray[0][0] == null || carSelectedArray.length == 0) {
arrayempty = true;
} else {
arrayempty = false;
}
if (arrayempty == true) {
carSelectedArray[0][0] = "test";
alert("output1:" + carSelectedArray[0][0]);
} else {
carSelectedArray[1][0] = "test2";
alert("output2:" + carSelectedArray[1][0]);
}
}
Your loop works well, however your didn't define your array well.
there is only 1 dimension here :
var carSelectedArray = [[null]];
So replace with this :
var carSelectedArray = [[],[]];
PS : null is not required
and at the beginning in your function, you define arrayempty to false, so you can remove this :
else {
arrayempty = false;
}
Solution here : https://plnkr.co/edit/Qikalr0jc54R3MRSea4G?p=preview
var carSelectedArray = [[],[]];
addRow(carSelectedArray);
addRow(carSelectedArray);
function addRow(carSelectedArray) {
var arrayempty = false;
if (carSelectedArray[0][0] == null || carSelectedArray.length == 0) {
arrayempty = true;
}
if (arrayempty == true) {
carSelectedArray[0][0] = "test";
alert("output1:" + carSelectedArray[0][0]);
} else {
carSelectedArray[1][0] = "test2";
alert("output2:" + carSelectedArray[1][0]);
}
}

Convert a jQuery object into JSON

I have a jQuery object with inside value and method also. I need to convert it into JSON.
Look at the following object:
I have self.pgrid.config.columnFields as above screenshot.
When I have converted this object into JSON and get that JSON back to object, it is not returning aggregateFunc and formatFunc.
Look at following screenshot of JSON.parse(JSON.stringify(self.pgrid.config.columnFields)):
Here I want to get those two methods also. How can I get them?
Code of generating object is as follows:
this.columnFields = (config.columns || []).map(function (fieldconfig) {
fieldconfig = ensureFieldConfig(fieldconfig);
return createfield(self, axe.Type.COLUMNS, fieldconfig, getfield(self.allFields, fieldconfig.name));
});
function ensureFieldConfig(obj) {
if (typeof obj === 'string') {
return {
name: self.captionToName(obj)
};
}
return obj;
}
function createfield(rootconfig, axetype, fieldconfig, defaultfieldconfig) {
var axeconfig;
var fieldAxeconfig;
if (defaultfieldconfig) {
switch (axetype) {
case axe.Type.ROWS:
axeconfig = rootconfig.rowSettings;
fieldAxeconfig = defaultfieldconfig.rowSettings;
break;
case axe.Type.COLUMNS:
axeconfig = rootconfig.columnSettings;
fieldAxeconfig = defaultfieldconfig.columnSettings;
break;
case axe.Type.DATA:
axeconfig = rootconfig.dataSettings;
fieldAxeconfig = defaultfieldconfig.dataSettings;
break;
default:
axeconfig = null;
fieldAxeconfig = null;
break;
}
} else {
axeconfig = null;
fieldAxeconfig = null;
}
var merged = mergefieldconfigs(fieldconfig, fieldAxeconfig, axeconfig, defaultfieldconfig, rootconfig);
return new Field({
name: getpropertyvalue('name', merged.configs, ''),
caption: getpropertyvalue('caption', merged.configs, ''),
sort: {
order: getpropertyvalue('order', merged.sorts, null),
customfunc: getpropertyvalue('customfunc', merged.sorts, null)
},
subTotal: {
visible: getpropertyvalue('visible', merged.subtotals, true),
collapsible: getpropertyvalue('collapsible', merged.subtotals, true),
collapsed: getpropertyvalue('collapsed', merged.subtotals, false) && getpropertyvalue('collapsible', merged.subtotals, true)
},
aggregateFuncName: getpropertyvalue('aggregateFuncName', merged.functions, 'sum'),
aggregateFunc: getpropertyvalue('aggregateFunc', merged.functions, aggregation.sum),
formatFunc: getpropertyvalue('formatFunc', merged.functions, null)
}, false);
}
function getpropertyvalue(property, configs, defaultvalue) {
for (var i = 0; i < configs.length; i++) {
if (configs[i][property] != null) {
return configs[i][property];
}
}
return defaultvalue;
}

Where is the bug in my recursive JSON parser?

I'd like to create a recursive function to parse json-like data as below. When key is xtype, a new class will be created. In particular, when xtype = gridpanel/treepanel, all the properties have to be its constructor argument, otherwise, properties will be added after class has been created.
My recursive function as below, I got an error 'too much recursion' at line 21 in ext-all.js.
Please take a look, how am I able to solve this problem?
codes in main program:
me.recursiveParser(null, data.json);
Ext.apply(me.root, me.parent);
me.desktopCfg = me.root;
recursiveParser function:
recursiveParser: function(nodeName, jsonData) {
var properties = {};
var isSpecial = false;
var isLeaf = true;
var parent, child, special;
//Base factor
for (var key in jsonData) {
var value = jsonData[key];
//To collect all the properties that is only initialized with '#'.
if (key.toString().indexOf("#") === 0) {
key = key.replace("#", "");
if(typeof(value) === "string"){
properties[key] = "'"+value+"'";
}else{
//Later, should have to deal with the empty value or array with no keys and only elements.
properties[key] = value;
}
if(key === "xtype"){
//To initialize the root
if(nodeName === null){
this.root = this.createNewObject(value, null);
}
if(value === "gridpanel" || value === "treepanel"){
isSpecial = true;
special = value;
}else{
child = this.createNewObject(value, null);
}
}
}else {
isLeaf = false;
}
}
if(isSpecial){
child = this.createNewObject(special, properties);
}
//To add the subnode and its properties to its parent object.
if (nodeName !== null && typeof(nodeName) === "string") {
if(child === null){
Ext.apply(parent, properties);
}else{
Ext.apply(parent, child);
}
}
if(isLeaf){
return;
}
for (var key in jsonData) {
var value = jsonData[key];
if (key.toString().indexOf("#") === 0) {
continue;
}else{
if(value === "[object Object]"){
for(var index in value){
this.recursiveParser(key, value[index]);
}
}else{
this.recursiveParser(key, value);
}
Ext.apply(this.root, parent);
}
}
}
createNewObject function:
createNewObject: function(objType, properties){
if(objType){
switch (objType){
case "gridpanel":
return new MyProg.base.GridPanel(properties);
break;
case "treepanel":
return new MyProg.base.TreePanel(properties);
break;
case "tabpanel":
return new MyProg.base.TabPanel();
break;
case "tab":
return new MyProg.base.Tabs();
break;
case "formpanel":
return new MyProg.base.Accordion();
break;
case "fieldset":
return new MyProg.base.FieldSet();
break;
case "textfield":
return new MyProg.base.Fields();
break;
case "panel":
return new MyProg.base.Accordion();
break;
default:
return new MyProg.base.Accordion();
};
};
}
data.json:
var data = {
"json": {
"#title": "BusinessIntelligence",
"#xtype": "tab",
"#layout": "accordion",
"items": [
{
"#title": "SalesReport",
"#ctitle": "SalesReport",
"#layout": "column",
"items": [
{}
]
},
{
"#title": "ContentPlayingReport",
"#ctitle": "ContentPlayingReport",
"#layout": "column",
"items": [
{}
]
},
{
"#title": "BusinessIntelligence",
"#ctitle": "BusinessIntelligence",
"#layout": "column",
"items": [
{}
]
}
]
}
}
I modified the recursion part, it looks more elegant now. All the xtype works just fine, except gridpanel, I've check DOM, everything is in there, but still got error message:
TypeError: c is undefined
...+g.extraBaseCls);delete g.autoScroll;if(!g.hasView){if(c.buffered&&!c.remoteSort...
ext-all.js (line 21, col 1184416)
I suspect it's an ExtJS bug. I'll try to find another way out.
recursion program:
recursiveParser: function (jsonData) {
var me = this;
var properties = {};
for ( var key in jsonData ){
var value = jsonData[key];
var items = (value.constructor === Array) ? [] : {};
if (value instanceof Object) {
if (isNaN(key)){
if (items.constructor === Array) {
for (var node in value){
items.push(me.recursiveParser(value[node]));
}
properties[key] = items;
} else {
properties[key] = me.recursiveParser(value);
}
} else {
return me.recursiveParser(value);
}
} else {
if (key.toString().indexOf('#') === 0){
key = key.replace('#', '');
properties[key] = value;
}
}
}
return properties;
}

Combining conditional statements in JavaScript

I have two variables that hold objects:
var person1 = {
name: "Joe",
study: false
};
var person2 = {
name: "Tom",
study: true
};
I've created two functions such that after a function is called, it will call both of these functions:
var person1study = function() {
if (person1.study === true){
person.study = false;
}
else {
person1.study = true;
}
};
var person2study = function() {
if (person2.study === true){
person2.study = false;
}
else {
person2.study = true;
}
};
Is there a way that I can combine these who functions into a single function that does that same thing?
Just declare the object as a parameter:
function toggleStudy(person) {
person.study = !person.study;
}
toggleStudy(person1); // invert the "study" flag on the "person1" object
The ! operator evaluates its operand as a boolean value, and returns the opposite value.
var personStudy = function(person) {
person.study = !person.study;
};
like this?

Categories

Resources