Update a rather large if statement of values to be an array - javascript

Here is a piece of JavaScript code that is rather large and clunky. I would like to take all of the setValue() code values and place it all into an array. At this point it seems as though I should just be able to take the values and place them into an array but I feel like I am skipping a step. Thanks for your help.
if (VS_group == "group") {
setValue('CORNER_1A_COUNT',"S06");
setValue('INBOARD_111_COUNT',"S06");
setValue('INBOARD_112_COUNT',"S06");
setValue('INBOARD_113_COUNT',"S06");
setValue('INBOARD_114_COUNT',"S06");
setValue('INBOARD_115_COUNT',"S06");
setValue('INBOARD_116_COUNT',"S06");
setValue('INBOARD_117_COUNT',"S06");
setValue('INBOARD_118_COUNT',"S06");
setValue('INBOARD_119_COUNT',"S06");
setValue('INBOARD_120_COUNT',"S06");
setValue('CORNER_1C_COUNT',"S06");
setValue('CORNER_1A',"RED");
setValue('INBOARD_111',"RED");
setValue('INBOARD_112',"RED");
setValue('INBOARD_113',"RED");
setValue('INBOARD_114',"RED");
setValue('INBOARD_115',"WHT");
setValue('INBOARD_116',"WHT");
setValue('INBOARD_117',"BLU");
setValue('INBOARD_118',"BLU");
setValue('INBOARD_119',"BLU");
setValue('INBOARD_120',"BLU");
setValue('CORNER_1C',"BLU");
setValue('ALLEY_1D_COUNT',"S06"); setValue('ALLEY_1P_COUNT',"S06");
setValue('ALLEY_1D',"WHT"); setValue('ALLEY_1P',"WHT");
setValue('CORNER_1B_COUNT',"S06");
setValue('INBOARD_131_COUNT',"S06");
setValue('INBOARD_132_COUNT',"S06");
setValue('INBOARD_133_COUNT',"S06");
setValue('INBOARD_134_COUNT',"S06");
setValue('INBOARD_135_COUNT',"S06");
setValue('INBOARD_136_COUNT',"S06");
setValue('INBOARD_137_COUNT',"S06");
setValue('INBOARD_138_COUNT',"S06");
setValue('INBOARD_139_COUNT',"S06");
setValue('INBOARD_140_COUNT',"S06");
setValue('CORNER_1D_COUNT',"S06");
setValue('CORNER_1B',"RED");
setValue('INBOARD_131',"RED");
setValue('INBOARD_132',"RED");
setValue('INBOARD_133',"RED");
setValue('INBOARD_134',"RED");
setValue('INBOARD_135',"RED");
setValue('INBOARD_136',"BLU");
setValue('INBOARD_137',"BLU");
setValue('INBOARD_138',"BLU");
setValue('INBOARD_139',"BLU");
setValue('INBOARD_140',"BLU");
setValue('CORNER_1D',"BLU");
}

You can store these values in an array and apply a loop on that array something like that
[ ['INBOARD_140_COUNT', 'S06'], ['INBOARD_141_COUNT', 'S07'] ].forEach(([key, value] => setValue(key, value));
When you run code snippet on StackOverflow it will give an error because "setValue()" is not defined, I wrote this just for better understanding

Related

forEach not changing values of array

availableButtons.forEach(function(part, index) {
console.log(this[index].title)
// this[index].title = intl.formatMessage(this[index].title);
}, availableButtons)
The code above prints the console as follows:
{id: "abc.btn.xyz", defaultMessage: "someMessage"}
This confirms that each object has an id but when I try to execute the commented code it throws an error saying [#formatjs/intl] An id must be provided to format a message.
I used the same array but only a single object separately as follows intl.formatMessage(availableButtons[0].title); this gave me the required result I am just not able to figure out. I tried various ways of passing values in forEach, what am I missing?
forEach does not actually mutate arrays. it's just a shorthand loop called on the array. It's hard to suggest a solution because your intent is not clear.
availableButtons = availableButtons.map(button => {
//do your mutations here
}
might be a start
I think Array#map works better for in this vade
availableButtons.map(part => {
return {
...part,
title: intl.formatMessage(part.title)
};
});
Access the array (availableButtons) directly and update (mutate) with forEach.
availableButtons.forEach(function (part, index) {
console.log("before: ", availableButtons[index].title);
availableButtons[index].title = intl.formatMessage(this[index].title);
console.log("after: ", availableButtons[index].title);
});

Javascript - Push to a new array dynamically?

Hello I am new to javascript so I'm sorry in advance if my explanation is not the best.
I am getting my data back from an array called myData. I have a condition statement which checks the page url and depending on the url I am pushing a specific index of an array to a new array called stateArray
At the moment I am using the push method like this:
stateArray.push(myData[1][5], myData[2][5], myData[3][5], myData[4][5], myData[5][5], myData[6][5], myData[7][5], myData[8][5], myData[9][5], myData[10][5], myData[11][5], myData[12][5], myData[13][5], myData[14][5], myData[15][5], myData[16][5], myData[17][5], myData][5])
the return of stateArray is giving back the data I am expecting but I am going to have ten different conditions and would like to know if there is a way of doing the push 17 times for every condition better?
Every element is the same for the condition. For example
if (url.includes('/states/') {
stateArray.push(myData[1][5], myData[2][5], myData[3][5], myData[4][5], myData[5][5], myData[6][5], myData[7][5], myData[8][5], myData[9][5], myData[10][5], myData[11][5], myData[12][5], myData[13][5], myData[14][5], myData[15][5], myData[16][5], myData[17][5], myData][5])
} else if (url.includes('/homes/) {
stateArray.push(myData[1][6], myData[2][6], myData[3][6], myData[4][6], myData[5][6], myData[6][6], myData[7][6], myData[8][6], myData[9][6], myData[10][6], myData[11][6], myData[12][6], myData[13][6], myData[14][6], myData[15][6], myData[16][6], myData[17][6], myData][6])
} else if (url.incldues('/retail/) {
stateArray.push(myData[1][7], myData[2][7], myData[3][7], myData[4][7], myData[5][7], myData[6][7], myData[7][7], myData[8][7], myData[9][7], myData[10][7], myData[11][7], myData[12][7], myData[13][7], myData[14][7], myData[15][7], myData[16][7], myData[17][5], myData][7])
}
Like I mentioned earlier I currently have 10 conditions and it is very difficult to maintain and update. Is there a way of generating the same results dynamically? I believe this can be done through a loop but I am not familiar with the syntax in regards to pushing at a specific index and ending at a specific index.
My expected outcome is a short handed way of going through each condition and pushing into the new Array.
You can use forEach:
if (url.includes('/states/')) {
myData.forEach(e => stateArray.push(e[5]));
} else if (url.includes('/homes/')) {
myData.forEach(e => stateArray.push(e[6]));
} else if (url.includes('/retail/')) {
myData.forEach(e => stateArray.push(e[7]));
}
(Also note you need a second ) at the end of your if to close off both the if and the includes)

How does Firebase rtdb query on a range of strings using orderByKey, startAt, endAt?

I have a firebase query that looks like this:
this.db.object(`...irrelevent`).query
.orderByKey().startAt(startVal).endAt(`${endVal}\uf8ff`).once('value').then(res => {
if (res.val()) {
// value returned
}
});
The structure of the area I'm querying looks like this
Based on the documentation found here when using the order by key function it first trys to sort the keys as numbers then lexicographically. As you can see in the image my keys are strings.
When startVal = "0015" and endVal = "0060" the query doesn't quite work as it returns this {0000-0015: "a", 0015-0075: "-M-BCseCnboNM9zB3o5S"}. From my understanding it should not be returning the first property of the object but when I make set startVal = "0795" and endVal = "0810" it returns:
{0000-0015: "a"
0015-0075: "-M-BCseCnboNM9zB3o5S"
0150-0240: "-M-BCxH9URUtYQg06wXE"
0300-0360: "-M-BD-YIAXO2FMVac0PW"}
This doesn't seem correct to me as it should return nothing because there exists no data between strings that startAt "0795" and endAt "0810".
My goal is to be able to pass in a startVal such as "0000" and an endVal such as "0030" and it return
{0000-0015: "a"
0015-0075: "-M-BCseCnboNM9zB3o5S"}
Can someone maybe set my understanding straight on how the startAt and endAt queries work when querying for a range of strings?
I think you're seeing some sort of array coercion going on here.
I tested with this JSON:
{
"0000-0015": "a",
"0015-0075": "-M-BCseCnboNM9zB3o5S",
"0150-0240": "-M-BCxH9URUtYQg06wXE",
"0300-0360": "-M-BD-YIAXO2FMVac0PW",
"key-0000-0015": "a",
"key-0015-0075": "-M-BCseCnboNM9zB3o5S",
"key-0150-0240": "-M-BCxH9URUtYQg06wXE",
"key-0300-0360": "-M-BD-YIAXO2FMVac0PW",
}
And this code:
function query(start, end) {
ref.orderByKey().startAt(start).endAt(end)
.once('value').then(snapshot => {
console.log(`startAt("${start}").endAt("${end}"): ${snapshot.numChildren()} result(s)`)
snapshot.forEach((child) => {
console.log(`"${child.key}"`)
});
});
}
query("0000", "0015");
query("0000-", "0015~");
query("0015-", "0060~");
query("key-0000", "key-0015");
And the output I got was:
startAt("0000").endAt("0015"): 0 result(s)
startAt("0000-").endAt("0015~"): 2 result(s)
"0000-0015"
"0015-0075"
startAt("0015-").endAt("0060~"): 1 result(s)
"0015-0075"
startAt("key-0000").endAt("key-0015"): 1 result(s)
"key-0000-0015"
All but that first result look correct, which is why I think the numbers are somehow being converted by (unpadded) array indices (so 0 instead of "0000"), which then doesn't work.
I'd recommend always prefixing numeric keys with an alphanumeric string, to prevent this sort of behavior, as I've done with the key- prefix above.
For my full testbed, see: https://jsbin.com/roluhip/2/edit?js,console

removing objects in an object in an array javascript

I've done some research on this issue. I am trying to manipulate an array of calculated values that looks like this in the console:
{nodeVoltages: Array(11), totalPower: Array(1), xlength: Array(11)}
nodeVoltages: Array(11)
0:48
1:47.71306060387108
2:47.250273223993105
3:46.59686907269243
4:45.71876416434013
5:44.53304242029258
6:42.745236969423615
7:Complex {re: 40.38334500994142, im:1.919295696316476, __ember1513267958317: "ember368"}
8:Complex { re:39.55961661806138, im:3.8933604519196416, __ember1513267958317: "ember369"}
This array is created dynamically through some math that I've come up with so there is no input data that I can give you. I'm trying to make the above array look like this:
{nodeVoltages: Array(11), totalPower: Array(1), xlength: Array(11)}
nodeVoltages: Array(11)
0:48
1:47.71306060387108
2:47.250273223993105
3:46.59686907269243
4:45.71876416434013
5:44.53304242029258
6:42.745236969423615
7:40.38334500994142
8:39.55961661806138
Using mathjs, I was able to evaluate my expressions and dynamically add the values into an array with the array.push command and display them. However, my code breaks once the imaginary values pop up in the results of my array.
How can I remove these imaginary numbers from my array? In other words, I need to remove the "im:" parts of the values when they begin to appear before I push them to the displayed array.
I tried to do this with some code I found from a previous answer to someone else's question (How do I remove a particular element from an array in JavaScript?) splice command like this:
var nodeVoltage2 = parser.eval(expression2);
//checks if there are imaginary values and removes them
if ("im" in nodeVoltage2) {
nodeVoltage2.splice(2,1)
}
//adds value to result array for analysis
nodeVoltages.push(nodeVoltage2);
but it returns in the console that "im is not defined".
Any help is greatly appreciated!
You can use the array map function.
Basically, we loop through the array. If the item has a .re property, we take that value only. If there is no .re property, we keep the value as is.
We can either write that in shorthand, as with result using the ternary operator and arrow function, or we can write it in a slightly more verbose but traditional way, as with resultTwo
let data = [
48
,47.71306060387108
,47.250273223993105
,46.59686907269243
,45.71876416434013
,44.53304242029258
,42.745236969423615
,{re: 40.38334500994142, im:1.919295696316476, __ember1513267958317: "ember368"}
,{ re:39.55961661806138, im:3.8933604519196416, __ember1513267958317: "ember369"}
]
let result = data.map((x) => x && x.re ? x.re : x);
let resultTwo = data.map(function(elem) {
// First, we need to check that the array element is not null / undefined
// We then need to check that it has a property called re that is also not null / undefined
if (elem != null && elem.re != null) {
// Just return the property we're interested in
return elem.re;
} else {
// Return the element as is
return elem;
}
});
console.log(result);
console.log(resultTwo);

can't get nested forEach to work in Javascript

So I guess the title is selfexplanatory. I have some code with nested forEach loops inside it. The loops are iterating over an array of chapter objects. Each object can have multiple child nodes and they again can have multiple child nodes, and so on.
I want to end up with one array which contains nested arrays with the child nodes.
So far my code looks like this:
exports.chapter = function(req, res) {
var chapters = [],
result = [];
chapters = exports.index(req, res);
chapters.forEach(function(chapter) {
if(chapter.orphan){
result.add({
'chapter': chapter,
'children': getChildren(chapter.children)
});
}
});
function getChildren(siblings) {
var children = [];
chapters.forEach(function(chapter) {
if($.inArray(chapter, siblings)){
children.add({
'chapter': chapter,
'children': getChildren(chapter.children)
});
}
});
return children;
};
};
I don't get any errors except for my page not loading. It doesn't write anything in my console. I think it's a problem in the setup but I'm unable to find out where at the moment. Really hope you guys can help.
Most likely problem is here:
if($.inArray(chapter, siblings)){
$.inArray is a horribly misnamed method: It returns an index, or -1 if not found, not a flag as the name implies. -1 is, of course, truthy; and 0 (a valid index), is falsey, so your if probably wants to be
if($.inArray(chapter, siblings) != -1){
// We found it...
}
or possibly
if($.inArray(chapter, siblings) == -1){
// We didn't find it
}
It's a bit strange.. I don't understand why you're using 'add' instead of 'push' method. If I try to "add" an object to an array I get an usual error. Don't you?

Categories