Check object for exact field match and only true values - javascript

How can I check if an object has the exact elements with true values?
This should be valid...
var checkIt = { 4: true, 15: true, 30: true, 75: true, id: 'anyString' };
...while those are invalid:
var checkIt = { 4: true, 15: false, 30: true, 75: true, id: 'anyString' };
var checkIt = { 4: true, 15: true, id: 'anyString' };
As a result I need true/false for this check.

One possible approach (ES6):
var props = [4, 15, 30, 75];
var isValid = props.every((prop) => checkIt[prop] === true);
... or, ES5 version:
var isValid = props.every(function(prop) {
return checkIt[prop] === true;
});
With this you can easily adjust the list of properties to check. Using every makes sure the check drops out right after encountering the first invalid property.
Note: you aren't quite clear on whether or not each property should be exactly true or just truthy; I assumed the former. If that's not the case, just drop === true part.

Related

How to remove false values from array?

I receive this in console
0: false
1: false
2: false
3: false
4: false
5: "scuole"
6: "scuole"
7: "scuole"
8: "scuole"
I need to remove all false and I have been trying to follow this on SO
and I tried
var scuole = [];
function bouncer(scuole) {
return scuole.filter(item => item);
}
bouncer([false, null, 0, NaN, undefined, ""]);
console.log(scuole);
But I still see false in console
Check comments for explaination.
var scuole = []
function bouncer(scuole) {
// .filter returns a new filtered array and in following case
// filtered array will return an array whos value is
// not equal to false
return scuole.filter(item => item !== false);
}
//when calling bouncer function which returns an array
// we need to store that returned array to scuole variable
// for future use.
scuole = bouncer([false, null, 0, NaN, undefined, ""]);
// expected result [ null, 0, NaN, undefined, ""]
console.log(scuole);
Array.filter returns a new array, so you would have to assign it to a new variable. Also you currently do not filter, you dont process the item. Try this:
var someArray = [true, true, false, true];
function bouncer(array) {
return array.filter(item => item !== false);
}
var otherArray = bouncer(someArray);
// expected output: [true, true, true]
Have a look at the documentation
You can use Boolean to cleanup all falsy values of an array.
const cleaned = [false, null, 0, NaN, undefined, ""].filter(Boolean);
// return "[]"
You can just use the "filter" function of JavaScript which will return you the filtered array. Please note, the filter will not update the original array hence you need to catch filtered array in a different array.
According to the snippet, I am returning the values except false. Let me know if you have any other issues or doubts.
var original_arr = [false, null, 0, NaN, undefined, ""]
var filtered_arr = original_arr.filter(function(item){return item != false})
console.log(filtered_arr);
var scuole = [false, null, 0, NaN, undefined, ""];
scuole= scuole.filter(item =>item!=false ||item!='false');
console.log(scuole);
you can do like this...
This should work:
const arr = [ false, null, NaN, 0, undefined, true, 'string', 1, 'text', 4.3, ''];
const newArr = arr.filter(e => e)
Should print out: [ true, 'string', 1, 'text', 4.3 ]

Convert and combine arrays in javascript

Hey I need your help in respect of converting arrays in javascript. Please look on my output data:
Answers: {
'0': { '0': 'ans 1' },
'1': { '0': 'ans 11', '1': 'ans 22', '2': 'ans 33' }
}
correctAnswers: {
'1': { '0': true, '1': true }
}
And I would like if indexes doesn't match set false, so I expect following array:
convertArray = [[false], [true, true, false]]
For this task I use following function
var choiceBoolean = [];
for(corrAns in Answers){
let tempArr = [];
Object.keys(Answers[corrAns]).forEach(k =>
tempArr[k] = correctAnswers[corrAns][k] || false)
choiceBoolean.push(Array.apply(null, tempArr).map(Boolean))
}
Unfortunately I receive error TypeError: Cannot read property '0' of undefined
You could map the keys from answer with another mapped array from the inner keys by checking correct answers.
This solution works with a check if the correct answer exist and then it checks the inner key.
correct[k] && correct[k][l] || false
^^^^^^^^^^ check first if exists
^^^^^^^^^^^^^ take a truthy value
^^^^^ if not take false
var answers = { 0: { 0: 'ans 1' }, 1: { 0: 'ans 11', 1: 'ans 22', 2: 'ans 33' } },
correct = { 1: { 0: true, 1: true } },
result = Object
.keys(answers)
.map(k => Object.keys(answers[k]).map(l => correct[k] && correct[k][l] || false));
console.log(result);

How to convert object to array only if its each value is true

I have selectedSizeList on my state.
selectedSizeList = {1: false, 2: true, 3: true, 4: true, 5: false}
How do I convert my selectedSizeList to this array?
[2, 3, 4]
Do I have better algorithm than this one? (I assume my solution is not correct)
let array = [];
Objects.keys(selectedSizeList).maps((item) => {
if(item.value) array.push(item.value)
);
return array;
You can use array#filter to filter out all keys with true value.
const selectedSizeList = {1: false, 2: true, 3: true, 4: true, 5: false};
const result = Object
.keys(selectedSizeList)
.filter(k => selectedSizeList[k])
.map(Number);
console.log(result);
First of all get the array keys using Object.keys() and then use filter() to filter only the true values like this.
var selectedSizeList = {1: false, 2: true, 3: true, 4: true, 5: false};
var keys = Object.keys(selectedSizeList);
var filtered = keys.filter(function(key) {
return selectedSizeList[key]
});
console.log(filtered);
Try this (O(n) solution):
selectedSizeList = {1: false, 2: true, 3: true, 4: true, 5: false};
var arr = [];
for (var key in selectedSizeList) {
if(selectedSizeList[key]){
arr.push(key);
}
}
console.log(arr);
You could use Object.keys() to return an`array that you can then use Array.prototype.filter() on to return a new array.
selectedSizeList = {1: false, 2: true, 3: true, 4: true, 5: false};
let array = Object.keys(selectedSizeList).filter((item) => {
if(selectedSizeList[item]) return item;
});
//returns [2,3,4]
You can use Object.keys to get an array that you can then filter for values equal to true which will return an array of numbers as a string. You can then map through the array using Number to convert the number strings to numbers which may or may not be necessary depending on what you plan to do with this result. I put this into a function that you can re-use or at least not have your object hard coded with.
var selectedSizeList = {1: false, 2: true, 3: true, 4: true, 5: false};
// Re-usable function not tied to specific object
const filterForTrueValue = (obj) => Object
.keys(obj)
.filter(k => obj[k])
.map(Number);
console.log(filterForTrueValue(selectedSizeList));

Replace javascript swich statement

I have a switch in javascript that I need to put it different.
How can I write this in a better way to avoid the switch?
var types = {
Int: 2,
Short: 3,
Long: 4,
Double: 5,
Decimal: 6,
String: 1,
Guid: 10,
Variant: 11,
};
switch (data.columnTypeId) {
case types.String:
case types.Guid:
case types.Variant:
self.GetStrings(data);
break;
case types.Int:
case types.Decimal:
case types.Short:
case types.Long:
case types.Double:
self.GetNumbers(data);
break;
default:
}
What about doing the same map, but map a function reference instead?
var columnTypes = {
2: self.GetNumbers,
3: self.GetNumbers,
4: self.GetNumbers,
5: self.GetNumbers,
6: self.GetNumbers,
1: self.GetStrings,
10: self.GetStrings,
11: self.GetStrings,
0: self.GetDefault //Guessing the default value would be 0
};
columnTypes[data.columnTypeId](data);
or with a safe check:
if (columnTypes.indexOf(data.columnTypeId) !== -1) {
columnTypes[data.columnTypeId](data);
} else {
self.GetDefault(data);
}
Or as #dandavis pointed out in a comment:
columnTypes[data.columnTypeId || self.getDefault](data);

Javascript array indexed by string

I have the below javascript function I want to optimise for my web app.
function DisplayToolTip(str) {
switch (str) {
case "a":
this.tooltip(xvalue,yvalue,text);
break;
case "b":
this.tooltip(xvalue,yvalue,text);
break;
case "c":
this.tooltip(xvalue,yvalue,text);
break;
default: break;
}
}
The switch statement may change i.e. json may need to add in a case "d" but the function exists so dont know how to update the above.
Normally in c# I would use a dictionary, so key would be "a" and value would be an object with properties xvalue,yvalue,text or value would be a string "this.tooltip(xvalue,yvalue,text);".
This way I could update the dictionary and the execution speed of 'DisplayToolTip' would be relatively the same no matter how many elements.
How do you create an array of objects indexed or quickly found using a string value in javascript?
Objects in javascript are like dictionaries.
var dictionary = {
a : ["xvalue","yvalue","text1"],
b : ["xvalue","yvalue","text2"]
}
console.log(dictionary["b"][2]); // will give you text2.
Demo
EDIT: Updated answer to contain arrays (as that is what the question is).
You can use the switch statement itself, with fall-through:
switch (str) {
case "a": case "b": case "c":
this.tooltip(xvalue,yvalue,text);
break;
default: break;
}
(But, as Qantas commented, the default case isn't necessary here.)
Or, it the browser supports it, you can use the indexOf method of arrays:
if (["a", "b", "c"].indexOf(str)) ...
I would do something like this:
var tooltipSettings={
a: {xvalue: 1, yvalue: 1, text: 'string a'},
b: {xvalue: 2, yvalue: 2, text: 'string b'},
c: {xvalue: 3, yvalue: 3, text: 'string c'}
};
function DisplayToolTip(str) {
if(tooltipSettings[str])
{
var settings=tooltipSettings[str];
this.tooltip(settings.xvalue, settings.yvalue, settings.text);
}
}
You could use a dictionary, witch is basically an plain object.
Javascript allows you to access an object property by string like you would access an array property like this:
var obj = {
test: 'text',
b: 4
}
console.log(obj['test'], obj.test);
console.log(obj['b'], obj.b);
So your code would look like this:
var pairs = {
'a': {
xvalue: 1,
yvalue: 1,
text: '1111'
},
'b': {
xvalue: 2,
yvalue: 2,
text: '2222'
}
};
function DisplayToolTip(str) {
var prop = pairs[str];
if (typeof prop !== 'undefined')
return this.tooltip(prop.xvalue, prop.yvalue, prop.text);
throw 'undefined prop ' + str;
}

Categories

Resources