Convert repeating "if" to "loop" instead (javascript) - javascript

I have JSON data coming with values like: status -> pla -> wea -> wea_0 -> stat
They're a series of wea_0, wea_1, wea_2,... inside pla
And I try to check if stat from them is acte
Here's my code:
if (status.pla.wea.wea_0.stat === 'acte') {
save_acte();
} else if (status.pla.wea.wea_1.stat === 'acte') {
save_acte();
} else if (status.pla.wea.wea_2.stat === 'acte') {
save_acte();
} else if (status.pla.wea.wea_3.stat === 'acte') {
save_acte();
} else if (status.pla.wea.wea_4.stat === 'acte') {
save_acte();
} else if (status.pla.wea.wea_5.stat === 'acte') {
save_acte();
} else if (status.pla.wea.wea_6.stat === 'acte') {
save_acte();
}
Please help me to turn this to loop or for instead.

Access the wea_x as properties with dynamic name:
for (let i = 0; i < 7; i++) {
if (status.pla.wea[`wea_${i}`].stat === "acte") {
save_acte();
}
}

You can use an array with all the possible indices of wea_* in it and iterate over that, checking each wea_* entry in turn. For example:
const status = {
pla: {
wea: {
wea_0: {
stat: "blah"
},
wea_1: {
stat: "blah"
},
wea_2: {
stat: "acte"
},
wea_3: {
stat: "blah"
}
}
}
};
function save_acte(i) {
console.log('saved acte ' + i);
}
[0,1,2,3].forEach(i => status.pla.wea['wea_' + i].stat === 'acte' ? save_acte(i) : '');
// or, if you're not using IE
[...Array(4).keys()].forEach(i => status.pla.wea['wea_' + i].stat === 'acte' ? save_acte(i) : '');

Related

How to make search case insensitive in Angular

I have a list of data names and I want to search through it. It should give result irrespective of the case.
this is what I have:
public groups = [{ name: '"Grx-1"', selected: false }, { name: '"Grx-man-2"', selected: false }, { name: '"Grx-up-3"', selected: false }];
queryGroups(groupName) {
this.groups = this.totalGroupsList.filter((group) => {
if (group.userId.includes(groupName) || group.dps.includes(groupName) || group.sourceType.includes(groupName)) {
return true;
} else {
let isRole = false;
group.role.forEach((role) => {
if (role.name.includes(groupName)) {
isRole = true;
return;
}
});
if (isRole === false) {
return false;
} else {
return true;
}
}
});
}
If I search for "Grx" I get all the results. I want that if I search for "grx" i should get all the results.
You can use toLowerCase()
role.name.toLowerCase().includes(groupName.toLowerCase())
You must use more than one search method :
queryGroups(groupName: string) {
this.groups = this.totalGroupsList.filter((group) => {
let isExist = this.searchFunc(groupName, group.userId)
|| this.searchFunc(groupName, group.dps)
|| this.searchFunc(groupName, group.sourceType)
if (isExist) {
return true;
} else {
let isRole = false;
group.role.forEach((role) => {
if (this.searchFunc(groupName, role.name)) {
isRole = true;
break;
}
});
return isRole !== false;
}
});
}
private searchFunc(searchKey, searchTarget): boolean {
if(!searchKey) {
return false;
}
return (searchTarget.toLocaleUpperCase().includes(searchKey.toLocaleUpperCase())) ||
(searchTarget.toUpperCase().includes(searchKey.toUpperCase())) ||
(searchTarget.includes(searchKey.toLocaleUpperCase())) ||
(searchTarget.includes(searchKey.toUpperCase())) ||
(searchTarget.toLocaleUpperCase().includes(searchKey)) ||
(searchTarget.toUpperCase().includes(searchKey)) ||
(searchTarget.includes(searchKey))
}

How to apply a settimeout in the VUEJS script?

I am developing my first application in vuejs and in the initial data upload in the script I need to modify the data I received from a call to the database.
Since I have modified the data it returns an error in the initial load of the page and after a few seconds it loads without problem.
I am trying to wrap this function in a settimeout but it returns an error in vuejs.
How can I apply this setTimeout?
here my script
<script>
export default {
data () {
return {
step: 1,
selected: 1
}
},
components: {
},
computed:{
selectedBasket() {
return !this.$store.getters.basket ? null : this.$store.getters.basket
},
items(){
return !this.$store.getters.items ? null : this.$store.getters.items
},
setTimeout(() => {
filteredEstimation(){
this.$store.getters.estimations.map(function(estimation) {
estimation.offers.map(function(offer) {
offer.name = offer.name.split(" ").reverse().slice(1).reverse().join(" ");
if (offer.name.includes("first")) {
offer.description = "first option";
}
if (offer.name.includes("second")) {
offer.description = "second option";
}
if (offer.name.includes("third")) {
offer.description = "third option";
}
});
});
return !this.$store.getters.estimations ? null : this.$store.getters.estimations.filter( item => item.id == this.selected )[0].offers
}, 700);
},
methods: {
getItemsName(item) {
if(item == 1){
return 'bag'
} else if(item == 2){
return 'paper'
} else {
return 'pen'
}
}
}
}
</script>
You're using that function inside the computed option, that's not allowed, you should define it in the mounted hook like :
<script>
export default {
data () {
return {
step: 1,
selected: 1
}
},
components: {
},
computed:{
selectedBasket() {
return !this.$store.getters.basket ? null : this.$store.getters.basket
},
items(){
return !this.$store.getters.items ? null : this.$store.getters.items
},
},
methods: {
getItemsName(item) {
if(item == 1){
return 'bag'
} else if(item == 2){
return 'paper'
} else {
return 'pen'
}
}
},
mounted(){
setTimeout(() => {
filteredEstimation(){
this.$store.getters.estimations.map(function(estimation) {
estimation.offers.map(function(offer) {
offer.name = offer.name.split(" ").reverse().slice(1).reverse().join(" ");
if (offer.name.includes("first")) {
offer.description = "first option";
}
if (offer.name.includes("second")) {
offer.description = "second option";
}
if (offer.name.includes("third")) {
offer.description = "third option";
}
});
});
return !this.$store.getters.estimations ? null : this.$store.getters.estimations.filter( item => item.id == this.selected )[0].offers
}, 700);
}
}
</script>

Break Nested some or map JavaScript

PC = {a:{ID: "abc",options:{x1:"100", x2:"200"}},b:{ID: "d",options:{x2:"100", x3:"200"}}}
pro = {
"pro": [
{
"pID": "abc",
"attributes": {
"xyz": [
"1",
"2",
"3"
],
"foo": "フルプレミアム"
}
}
]
}
functionX() {
let isND = true;
if (pro === null || pro === [] || pro.length === 0) {
return isND;
} else if (pro.length > 0) {
some(PC, (p) => {
some(p.options, (o, k) => {
some(pro, (item) => {
if (p.ID === item.pID && k === 'xyz') {
if (item.attributes[k] !== []) {
isND = false;
}
} else if (p.ID === item.pID && k !== 'xyz') {
if (item.attributes[k] !== '') {
isND = false;
}
}
});
});
});
}
return isND;
}
I have to iterate through 3 different collections to check my condition and return a value. I am trying to exit the nested some or map if one of my if- else conditions satisfy. I tried passing return true after isND = false but doesn't work. Can someone help resolve this.
Array.prototype.some() will exit early if any of the callbacks return true so you could return the result that way.
It's not very clear but it seems you want to use this "early exit" feature while returning the inverse. How about something like this...
// ignoring "if (pro === null || pro === [] || pro.length === 0)" for this example
// return the inverse
return !Object.values(PC).some(({ ID, options }) => {
return Object.entries(options).some(([k, o]) => {
// here "k" is one of your "x1", "x2", etc keys
// and "o" is the corresponding value
return pro.pro.some(item => {
// return "true" if any of your "conditions" are met
})
})
})
return Object.values(PC).some(({ ID, options }) => {
return Object.entries(options).some(([k]) => {
return (pro.pro).some((item) => {
if (condition) {
if (condition) {
return false;
}
return true;
} else if (condition) {
if (condition) {
return false;
}
return true;
}
return null;
});
});
});
// Haven't returned the inverse of outer function

JS find key value pair in encapsulated object

I have a big problem and I need your help.
I have a object like this:
{
folder1: {
folderid: 1,
files: {
name: "yeah.txt"
},
folder2: {
folderid: 2
folder3: {
folderid: 3
}
}
},
folder4: {
folderid: 4
}
}
and I want to search for the key "folderid = 3" and find the object.
How can I do this in JavaScript?
Kind regards and thanks for your help
I came to a more generalised solution, that supports multiple properties check:
function search(obj, properties){
if(Object.keys(properties).every(function(key){
return obj[key] === properties[key];
})) {
return obj;
} else {
Object.keys(obj).forEach(function(key){
var child = obj[key];
if(child !== null && typeof child === 'object'){
return search(child, properties);
}
});
return false;
}
}
demo: http://jsfiddle.net/dzs1orbw/
You can use a DSF algorithm to do this: http://jsfiddle.net/L5b07bt6/
var obj = {
folder1: {
folderid: 1,
files: {
name: "yeah.txt"
},
folder2: {
folderid: 2,
folder3: {
folderid: 3,
caption: "I got it!"
}
}
},
folder4: {
folderid: 4
}
};
function find(root, id) {
if (root.folderid == id) return root;
if (typeof root !== 'object') return null;
var key, val;
for (key in root) {
val = find(root[key], id);
if (val != null) return val;
}
return null;
}
var result = find(obj, 3);
if (!result) alert("Not found!");
else alert("Found: " + result.caption);
and here another one:
function findByKey (object, searchKey){
if(typeof object !== 'object'){
return false;
}
for(var key in object){
if(object[key] === searchKey){
return object;
} else {
if(typeof (object[key] === 'object')){
var result = findByKey(object[key], searchKey);
if(result){
return result;
}
}
}
}
}
http://jsfiddle.net/mattposch/ebmd8xtk/

Simple JavaScript empty string check, what does (an empty string) mean and why is it failing?

Here's my code:
$("#ddlCiudad").change(function () {
var idCity = $("#ddlCiudad").val();
$.getJSON("/ProductCheckout/GetPriceForLocation", { cityId: idCity, productId: idProduct, type: "land" },
function (cityData) {
console.log("Recieved json data.");
landCost = cityData.LandCost;
$("#billingshippingcost").text(landCost);
console.log("Assigned value of LandCost");
airCost = cityData.AirCost;
console.log("Assigned value of AirCost");
console.log(landCost); //Logs: 25,00
console.log(airCost); //Logs: "(an empty string)"
if (landCost == "") {
$(".land").removeClass("land").addClass("land-disabled");
}
else {
$(".land-disabled").removeClass("land-disabled").addClass("land");
}
if (airCost = "") {
$(".air").removeClass("air").addClass("air-disabled");
}
else {
$(".air-disabled").removeClass("air-disabled").addClass("air");
}
}
);
});
That if statement is not being fired, any suggestions on why it's not firing?
Maybe an empty string isn't the same as "" in Javascript.
Try:
if (!airCost) {
$(".air").removeClass("air").addClass("air-disabled");
}
else {
$(".air-disabled").removeClass("air-disabled").addClass("air");
}

Categories

Resources