Combining two object in javascript and convert to String - javascript

I am hoping I am missing something obvious here, but I have tried for the past half day to set two variables to combine in a certain format in Javascript I can do it as a string, however I need it in a different format.
If I select on option from the check boxes {"GILLS":"7"} works fine however if two options are selected query1 should look like [{"GILLS":"1"},{"GILLS":"7"}]. I cannot use += to the variable as this kicks out an unexpected token error.
var Query1 = '';
var Query3 = '';
if ($('input[name=checkbox2a]:checked').length > 0) {
var Query3 = {"GILLS":"7"};
}
if ($('input[name=checkbox2b]:checked').length > 0) {
var Query3 = {"GILLS":"1"};
}

Try
var Query1 = [];
and in your function use
Query1.push({"GILLS":"1"})
So the change will be like below
var Query1 = [];
var Query3 = [];
if ($('input[name=checkbox2a]:checked').length > 0) {
Query3.push({"GILLS":"7"});
}
if ($('input[name=checkbox2b]:checked').length > 0) {
Query3.push({"GILLS":"1"});
}
then you can use join will give you string
Query3.join(", ")

Make an array out of Query3, if you still want a string at the end, use .join("").
var Query1 = '';
var Query3 = [];
if ($('input[name=checkbox2a]:checked').length > 0) {
Query3.push({"GILLS":"7"});
}
if ($('input[name=checkbox2b]:checked').length > 0) {
Query3.push({"GILLS":"1"});
}
Query3 = Query3.join(""); // back to string, if you so like

You're causing pain for yourself if you take the approach that sometimes the variable is of type Object ({"GILLS": "1" }) and sometimes it is of type List ([{"GILLS":"1"},{"GILLS":"7"}]).
Since it sometimes needs to be a list, make sure it's always a list. Even though sometimes it's a list of length 1. Then when you are reading that value, you never need conditional logic to deal with two potential types.
So, it's always a List:
var query3 = [];
... and then it's easy to manipulate:
if(...) {
query3.push( { "GILLS": "7" } );
}
if(...) {
query3.push( { "GILLS": "1" } );
}

At first, you are declaring same variable in a different scope. Don't do this unless uou know what you are doing. In other words use var keyword only once for a variable in a "space" when you are using this particular variable.
An advantage/disadvantage (chose one ;)) of javascript is that there is no type control. If You type var Query3 = ''; and then Query3 = {"GILLS":"7"}; interpreter will execute this without any complaints beside that there is high probability, that this is not exactly what you want to do ;). In this case it makes variable Query3 an empty string and then makes it an object.
In Your case, You want to have in result an array of objects. At first declare var Query3=[]; and then use a push method on it (Query3.push({});) to add elements.

Related

jQuery and XML, find object that contains children with multiple specific values

For a project I have data stored in XML like this:
<xml>
<sprites>
<sprite>
<name>Tile1</name>
<lat>1</lat>
<lng>2</lng>
</sprite>
<sprite>
<name>Tile2</name>
<lat>3</lat>
<lng>4</lng>
</sprite>
</sprites>
<xml>
Through jQuery I want to get a tile object that matches two child values, the lat and lng values.
I found this post which was of great help, but sadly it only has an example of how to search for one matching value. Here's the code I have up to now:
// xml stored in 'xml' var
var findLat = 3;
var findLng = 4;
var mapSprites = $(xml).find("sprites");
var getSprite = $(mapSprites).find("sprite").filter(
function() {
return $(this).find('lat').text() == findLat;
},
function() {
return $(this).find('lng').text() == findLng;
}
);
Sadly getSprite is undefined, as I'm guessing you can't use the filter function as I've tried to use it? The example I linked to has one function as filter and seems to work, but comma separating doesn't seem to work as an AND, which is what I need.
The goal is to be able to give the function a lat and lng value and me being able to extract the <name> value.
Would be thankful for a push in the right direction, I'm pretty new to XML and parsing it through jQuery.
filter does not take multiple arguments. So combine it into one using "and".
var findLat = 3;
var findLng = 4;
var mapSprites = $(xml).find("sprites");
var getSprite = mapSprites.find("sprite").filter(
function() {
const node = $(this);
return Number(node.find('lat').text()) === findLat &&
Number(node.find('lng').text()) === findLng;
}
);

JavaScript Clearing Array Value

I have an array of arrays in JavaScript that I'm storing some values in, and I'm attempting to find a way to clear the value within that array when the user removes the specified control from the page, however I'm not finding a good way to do this and anything I try doesn't seem to be working.
What is the best method for clearing the value in the array? I'd prefer the value to be null so that it's skipped when I iterate over the array later on.
I've tried to do MyArray[id][subid] = '' but that still is technically a value. I've also tried to do MyArray[id][subid].length = 0 but that doesn't seem to do anything either. Trying to grab the index and splice it from the array returns a -1 and therefore doesn't work either.
var MyArray;
window.onload = function(){
MyArray = new Array();
}
function EditValuesAdd(){
var Input = document.getElementById('Values-Input').value;
var ID = document.getElementById('FID').value;
var ValueID = ControlID(); // generate GUID
if (!MyArray[ID]) MyArray[ID] = new Array();
MyArray[ID][ValueID] = Input;
document.getElementById('Values').innerHTML += '<a href="#" id="FV-' + ValueID + '" onclick="EditValuesRemove(this.id)"/><br id="V-' + ValueID + '"/>';
}
function EditValuesRemove(id)
{
var ID = document.getElementById('FID').value;
document.getElementById(id).remove();
document.getElementById(id.replace('FV-', 'V-')).remove();
MyArray[ID][id.replace('FV-', '')] = '';
}
I've also tried to do an index of and then splice it from the underlying array but the index always returns -1.
var Index = MyArray[ID].indexOf(id.replace('FV-', ''));
MyArray[ID].splice(Index, 1);
Setting the length to zero has no effect either.
MyArray[ID][id.replace('FV-', '')].length = 0;
I would expect that one of the methods above would clear out the value and make it null so that it is skipped later on but all of the methods I've found and tried so far leave some non-null value.
What you need is an object (a Map), not an array (a list).
Here's a basic idea of how to do it :
MyArray = {};
....
if (!MyArray[ID]) MyArray[ID] = {}
MyArray[ID][ValueID] = Input;
...
delete MyArray[ID][id.replace('FV-', '')];
Check here for more information : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
In the end I used an array of objects MyArray = [] and then using splice/findindex to remove it from the array:
function RemoveItem(id)
{
var Index = MyArray.findIndex(a => a.ID == id.replace('FV-', ''));
MyArray.splice(Index, 1);
document.getElementById(id).remove();
document.getElementById('FVB-' + id.replace('FV-', '')).remove();
}
It doesn't solve the actual question asked but I don't know if there really is an answer since I was using arrays in the wrong manner. Hopefully this at least points someone else in the right direction when dealing with arrays and objects.

Unable to get the value from json object in javascript

unable to get the value_1 from dataObject.Showing undefined.
var errorMessage;
var dataObject ={"project_type":"{\"value_1\":\"Ground Mount\"}"};
var project_type_str = dataObject['project_type'];
project_type_str = JSON.stringify(project_type_str);
if (project_type_str != null && project_type_str.length != 0) {
errorMessage = '';
} else {
errorMessage = 'Please select a project type';
}
alert(project_type_str);
var responseJson = {};
var project_type_obj = JSON.parse(project_type_str);
alert(project_type_obj);
var value = project_type_obj["value_1"];
alert(value);
Thanks for your answers.Please help me
project_type_str is already a string, so no need to JSON.stringify it.
The code should work fine if you remove the line
Remove this line
project_type_str = JSON.stringify(project_type_str);
A comparison for your better understandability
With original code
With the line removed
You don't need those extra quotes and escape characters to define the object. Do this:
var dataObject = {
"projectType": {
"value1": "groundMount"
}
};
EDIT: I now see that you were intentionally writing JSON in its string representation so that you can parse it later. I hope that you have a special use case where you'd need to do something like that; otherwise, defining the object like I have will be much easier to deal with.

Get array from dynamic variable

I'm sure this is really simple, I just can't work out how to do it.
I want to dynamically make an array from one variable equal to another:
var pageID = document.getElementsByClassName('page_example')[0].id;
Let's say this returned an id of page_1
var page_1 = ['value1','value2','value3'];
var page_2 = ['value4','value5','value6'];
var page_3 = ['value7','value8','value9'];
var page_array = (then have the associated pageID's array here)
So in this example,
page_array would equal ['value1','value2','value3']
Instead of storing the array in separate variables, store them in an object with the ids as the key:
var pages = {
page_1: ['value1','value2','value3'],
page_2: ['value4','value5','value6'],
page_3: ['value7','value8','value9']
}
You can access the arrays as though the object was an assosiative array:
var pageID = "page_1";
var pageArray = pages[pageID];
Depending on what you would like to achieve, you can one of two or three methods.
What I consider the easiest method is an if/else statement:
if (condition) {
page_array = page_1.slice(0);
} else if (other condition) {
page_array = page_2.slice(0);
} else if...
Another method you can use, again depending on what your ultimate goal is, would be a for loop:
for (var i = 0; i < numOfDesiredLoops; i++) {
page_array = page_1.slice(0, i);
}
Or you could use a combination of both:
for (var i = 0; i < numOfDesiredLoops; i++) {
if (condition) {
page_array = page_1.slice(0);
} else if (other condition) {
page_array = page_2.slice(1);
} else if...
}
With more information on why you need this variable to change, I can give you a better answer.
edit: keep in mind the arguments of .slice() can be whatever you want.

Using a generic prompt function to get data for several variables and change the prompt message each time

A bit of a lengthy title, but I couldn't think of any way to cut it down. What I want to do is see if I can make a prompt function that I can use multiple times to store information for multiple variables. The problem is I want the message in the prompt to change each time so the user knows what I'm asking for. I think there's some way I can pass a a line of text to the function so it knows what to tell the user. Here's roughly what I have so far:
function getNum()
{
var userInput
do
{
userInput = prompt([THIS IS WHERE I WANT THE TEXT TO CHANGE]) * 1;
}while (isNaN(userInput));
return userInput;
}
Any tips?
does this work.
function getNum(message)
{
var userInput
do
{
userInput = prompt(message) * 1;
}while (isNaN(userInput));
return userInput;
}
This will return an array of answers to each question defined in the prompts array.
function getNum() {
var userInput = [];
var prompts = ["Question1","Question2","Question3"];
for( var i = 0; i < prompts.length; i++ ) {
userInput[i] = prompt(prompts[i]);
}
}
Edit: I don't think that's what you're asking for, though.
Well I've found out how do accomplish what I was trying to. Hopefully this will be helpful to anyone in a similar situation.
Here's the function:
function getNum(displayString)
{
var userInput;
do
{
userInput = prompt(displayString,"")*1;
}while(isNaN(userInput));
return userInput;
}
And here's how I passed a string:
Ex)
var userTable = getNum("The first number is the times table");
For some reason the javascript would never be able to execute unless I worded the parameter like this.
Display string is the string I pass to the function, and when I declare and initialize the variable "userTable", I call the function, passing the string in the brackets as the parameter. This is what would play the role of "displayString" in the function.
let lengthofArry = prompt("Talk length of arry");
let newarry = [];
let userdata = 0;
for (let i = 0; i< lengthofArry; i++) {
let userdata = prompt(`Enter Array value ${i+1} `);
userdata = parseInt(userdata)
newarry.push(userdata);
};
console.log(newarry);

Categories