I want to perform a if statement and only get the details from a key if a given value is present under the key field.
For example, given the below dataset
I want to search if the database 'jokes' contain text like 'HaHa', if it does, I want to make reference to the ID of that data set, in this case 'K9WJOahmsqmuPQbl8wD' and then perform a if statement only on the data under this ID.
for example,
var MyFirebase = data.val();
var keys = object.keys(MyFirebase); // This line gets all the keys in the table
// This loops through the keys
for (var i = 0; i < keys.length; i++){
var key = keys[i];
var author = MyFirebase[key].author;
var jokeText= MyFirebase[key].jokeText;
var votes= MyFirebase[key].votes;
// Now I want to carry out a if statement, that checks if given text is inside that id
IF jokeText == "HAHA" && author == "test"
getID = getParentID
IF getID IS parent of "HAHA" && "test"
DOsomething
ELSE
DOsomethingELSE
} // end for loop
I hope I have made myself clear, if not, please let me know :)
Related
I'm currently facing a difficulty in my codes.
First i have an array of objects like this [{Id:1, Name:"AML", allowedToView:"1,2"}, {Id:2, Name:"Res", allowedToView:"1"}...] which came from my service
I assign it in variable $scope.listofResource
Then inside of one of my objects I have that allowedToView key which is a collection of Id's of users that I separate by comma.
Then I have this code...
Javascript
$scope.listofResource = msg.data
for (var i = 0; i < msg.data.length; i++) {
First I run a for loop so I can separate the Id's of every user in allowedToView key
var allowed = msg.data[i].allowedToView.split(",");
var x = [];
Then I create a variable x so I can push a new object to it with a keys of allowedId that basically the Id of the users and resId which is the Id of the resource
for (var a = 0; a < allowed.length; a++) {
x.push({ allowedId: allowed[a], resId: msg.data[i].Id });
}
Then I put it in Promise.all because I have to get the Name of that "allowed users" base on their Id's using a service
Promise.all(x.map(function (prop) {
var d = {
allowedId: parseInt(prop.allowedId)
}
return ResourceService.getAllowedUsers(d).then(function (msg1) {
msg1.data[0].resId = prop.resId;
Here it returns the Id and Name of the allowed user. I have to insert the resId so it can pass to the return object and it will be displayed in .then() below
return msg1.data[0]
});
})).then(function (result) {
I got the result that I want but here is now my problem
angular.forEach(result, function (val) {
angular.forEach($scope.listofResource, function (vv) {
vv.allowedToView1 = [];
if (val.resId === vv.Id) {
vv.allowedToView1.push(val);
I want to update $scope.listofResource.allowedToView1 which should hold an array of objects and it is basically the info of the allowed users. But whenever I push a value here vv.allowedToView1.push(val); It always updates the last object of the array.
}
})
})
});
}
So the result of my code is always like this
[{Id:1, Name:"AML", allowedToView:"1,2", allowedToView:[]}, {Id:2, Name:"Res", allowedToView:"1", allowedToView:[{Id:1, Name:" John Doe"}]}...]
The first result is always blank. Can anyone help me?
Here is the plunker of it... Plunkr
Link to the solution - Plunkr
for (var i = 0; i < msg.length; i++) {
var allowed = msg[i].allowedToView.split(",");
msg[i].allowedToView1 = [];
var x = [];
Like Aleksey Solovey correctly pointed out, the initialization of the allowedToView1 array is happening at the wrong place. It should be shifted to a place where it is called once for the msg. I've shifted it to after allowedToView.split in the first loop as that seemed a appropriate location to initialize it.
I have a $localstroge with the below stored value:
{"EmployerDetails":{"Distance":30,"EmpLatitude":51.3353899,"EmpLongitude":-0.742856,"EmpNo":39424,"Insitution":null,"PlaceName":"Camberley","TalentPoolLicences":[{"Membership":[{"Identity":39424,"Name":"Weydon Secondary School"}],"TalentPoolType":1},{"Membership":[{"Identity":2,"Name":"North East Hampshire"},{"Identity":4,"Name":"Surrey"},{"Identity":8,"Name":"Surrey"}],"TalentPoolType":3}]},"FacetFilters":{"LastActivity":0,"LocationFilterType":1,"fullorparttime_pex":null,"religion":null,"soughtphase_swk":null,"soughtrole_swk":null,"soughtsubject_swk":null},"LookingFor":null,"OrderBy":null,"PageIndex":1,"PageSize":40}
How can I get the Identity value out from it that sits inside EmployerDetails. I have tried below but it never gets inside if condition:
for (var i = 0; i < localStorage.length; i++) {
if (localStorage.getItem(localStorage.key(i)) === 'EmployerDetails')
{ console.log('hello'); }
}
Any help on this please?
As you're searching for nested key first you need to grab the object and also need to parse it to JSON with JSON.parse then you can proceed as we do in case on normal javascript object
localStorage.getItem('signup-prefs')
This gives me a string containing my object
""name":"google","oauth_version":"2.0","oauth_server":"https://accounts.google.com/o/oauth2/auth","openid":"","username":""}"
After parsing it we can get the object and now we can find the desired property.
JSON.parse(localStorage.getItem('signup-prefs'))
Object {name: "google", oauth_version: "2.0", oauth_server: "https://accounts.google.com/o/oauth2/auth", openid: "", username: ""}
Coming to your problem
Let's say your employee information is like this i am not showing all the fields here.
var empData = {"EmployerDetails":Distance":30,"EmpLatitude":51.33538}}
Then you set the key like this
localstorage.setItem('empData', JSON.stringify(empData))
Now get the string object by key parse it to Json and find the desired key from the object loop over it to get the result.I haven't tested it but i am confident it will work. Let me know if not.
for (var i = 0; i < localStorage.length; i++) {
if (localStorage.key(i) === 'empData') {
// Parse the string to json
var empData = JSON.parse(localStorage.getItem('empData'));
// get all the keys
var keys = Object.keys(empData);
for (var idx = 0; idx < keys.length; idx++) {
// find the desired key here
if (keys[idx] == 'EmployeeDetails') {
var empDetails = empData[keys[idx]]
}
}
}
}
One important thing about your code is
this statement localStorage.key(i)) === 'EmployerDetails' returns either true or false and writing like this
if(localStorage.getItem(localStorage.key(i)) === 'EmployerDetails') will never was executed because you didn't have any key with that name(In practice we should never use keyword as key) .
Did you try to convert it to the json object and then gets the values out?
I am working with the google sites list item.
The classes are Here and Here
I have been able to iterate through the columns and put all of the column headers in to one array with the following code.
//Global
var page = getPageByUrl(enter URL here)
var name = page.getName();
function getInfo() {
var columns = page.getColumns();
//Get Column Names
for (var j in columns) {
var cName =columns[j].getName();
columnList.push(cName);
}
}
Now I want to be able to get each row of the listitem and put it in its own array.
I can add the variable
function getInfo() {
var columns = page.getColumns();
var listItems = page.getListItems();//new variable
//Get Column Names
for (var j in columns) {
var cName =columns[j].getName();
columnList.push(cName);
}
}
Now that I have the variable the output is [ListItem, ListItem, ListItem, ListItem]
So I can use a .length and get a return of 4.
So now I know I have 4 rows of data so based on my wants I need 4 arrays.
Small interjection here, Not a coder by trade but code as a precursor to wants becoming needs.
A buddy of mine who is a JS coder by trade showed me this code which does work. With the logger added by me.
for (var i in listItems) {
if (listItems.hasOwnProperty(i)) {
item = listItems[i];
for (var x = 0; x < columnList.length; x++) {
attrib = item.getValueByName(columnList[x]);
Logger.log("Logging value of get list page get value by name = " + columnList[x] + " " + attrib);
}
}
}
Which brings the total code to
var name = page.getName();
var listItems = page.getListItems();
var listCount = listItems.length
var listList = [];
var columns = page.getColumns();
var name = columns[0].getName();
var item, attrib = 0;
var columnList = [];
Logger.log(listItems);
Logger.log(name + " was last updated " + page.getLastUpdated());
Logger.log(name + " was last edited " + page.getLastEdited());
var listCount = 0;
//Get Column Names
for (var j in columns) {
var cName =columns[j].getName();
columnList.push(cName);
}
Logger.log(columnList);
// Get index of Due Date
var dueDateValue = columnList.indexOf("Due Date");
Logger.log("The index of due date is " + dueDateValue);
for (var i in listItems) {
if (listItems.hasOwnProperty(i)) {
item = listItems[i];
for (var x = 0; x < columnList.length; x++) {
attrib = item.getValueByName(columnList[x]);
Logger.log("Logging value of get list page get value by name = " + columnList[x] + " " + attrib);
}
}
}
}`
Forgive the above code as it has been a bit of a sketch pad trying to work this out.
I am a bit behind on understanding what is happening here
for (var i in items) { // This is for each item in the items array
if (items.hasOwnProperty(i)) {
if items is an array, how can we use has own property? Doesn't that belong to an object? Does an array become an object?
My questions are two category fold.
Category # 1
What is happening with the hasOwnProperty?
-Does the array become an object and thus can be passed to .hasOwnProperty value
Category # 2
Is this the only way to take the values from the listitem and populate an array
- If it is, is there some way to delimit so I can pass each row into it's own array
- If it isn't , why does it work with the hasOwnProperty and why doesn't it work without it in the example below
for (var i in listItems) {
for (var y = 0; y < columnList.length; y++) {
item = listItems[i];
listList = item.getValueByName(columnList[x]);
Logger.log("Logging my version of list naming " + listList);
}
In which I get a "Invalid argument: name (line 41" response. Highlighting the
listList = item.getValueByName(columnList[x]);
Not looking for a handout but I am looking to understand the hasOwnPropertyValue further.
My current understanding is that hasOwnValue has to do with prototyping ( vague understanding ) which doesn't seem to be the case in this instance
and it has to depend on a object which I described by confusion earlier.
To clarify my want:
I would like to have each row of listitems in its own array so I can compare an index value and sort by date as my current column headers are
["Project", "Start Date" , "End Date"]
Any and all help is much appreciated for this JS beginner of 2 weeks.
An array can be inside of an object as the value of a member:
{"myFirstArray":"[one,two,blue]"}
The above object has one member, a name/value pair, where the value of the member is an array.
Here is a link to a website that explains JSON.
Link To JSON.org
JSON explained by Mozilla
There are websites that will test the validity of an object:
Link to JSONLint.com
An array has elements, and elements in an array can be other arrays. So, there can be arrays inside of arrays.
.hasOwnProperty returns either true or false.
Documentation hasOwnProperty
Interestingly, I can use the hasOwnProperty method in Apps Script on an array, without an error being produced:
function testHasProp() {
var anArrayTest = [];
anArrayTest = ['one', 'two', 'blue'];
Logger.log(anArrayTest);
var whatIsTheResult = anArrayTest.hasOwnProperty('one');
Logger.log(whatIsTheResult);
Logger.log(anArrayTest);
}
The result will always be false. Using the hasOwnProperty method on an array doesn't change the array to an object, and it's an incorrect way of using Javascript which is returning false.
You could put your list values an object instead of an array. An advantage to an object is being able to reference a value by it's property name regardless of where the property is indexed. With an array, you need to know what the index number is to retrieve a specific element.
Here is a post that deals with adding properties to an object in JavaScript:
StackOverflow Link
You can either use dot notation:
objName.newProperty = 'newvalue';
or brackets
objName["newProperty"] = 'newvalue';
To add a new name/value pair (property) to an object.
This doesn't work but I can't see why it wouldn't? any help people? :)
params = qs.split("=", 2),
id = params[1];
if(id.indexOf("?") != -1){
id = id.split("?", 1);
}
basically I want to change the value of 'ID' if the IF statement is true, if not.. it skips it and the value Id remains the default.
Thanks
The result of id = id.split("?", 1) is an array (of at most 1 item), but I think you want id to be a string. That would explain why id is not a string like you want.
I agree with the other comments. Please show us the URL string you want to parse and tell us which piece you're trying to get. Usually, you look for ? first, separate after that and then divide up various key=value sections.
If you had a URL like this:
http://www.example.com?foo=bar
Here's a simple function that gets you all the query parameters into an object:
function getParms(url) {
var sections, key, pieces = url.split("?");
var results = {};
if (pieces.length > 1) {
sections = pieces[1].split("&");
for (var i = 0; i < sections.length; i++) {
key = sections[i].split("=");
results[key[0]] = key[1];
}
}
return(results);
}
Working demo: http://jsfiddle.net/jfriend00/kNG3u/
I have a form that currently only parses the first input variable in the POST.
I have had to add multiple variables, so I would like the function to loop through and grab all the input parameters and add to the POST
Here's the working code for grabbing the first name and value.... How can I get it to check the form and grab all custom name's and variables.
example here
// dynamically add key/value pair to POST body
function read_custom_param(){
var nameEl = document.getElementById("custom_name");
var valueEl = document.getElementById("custom_value");
// save custom param name and value
var cust_param_name = nameEl.value;
var cust_param_value = valueEl.value;
// remove old custom param form elements
if (valueEl.parentNode && valueEl.parentNode.removeChild){
valueEl.parentNode.removeChild(valueEl);
}
if (nameEl.parentNode && nameEl.parentNode.removeChild){
nameEl.parentNode.removeChild(nameEl);
}
// add new custom param form elements
var el=document.createElement("input");
el.type="text";
el.name=cust_param_name;
el.value=cust_param_value;
document.getElementById("dcapiform").appendChild(el);
}
Kind Regards,
Chris
for whatever purpose ur trying to send ambiguous field names to the server, here is what ur looking for (u should consider a smarter way, may br processing on the server side instead)
var elems = document.getElementsByTagName("input");
var arr = [];
for (var i = 0; i<elems.length; i++){
if (elems[i].type != "text") continue;
if (elems[i].name.indexOf("custom_name") < 0) continue;
var index = parseInt(elems[i].name.substring(11)); // you should rename custom_name to custom_name1, and so for custom_value
arr[arr.length] = elems[i].value+"=" + elems["custom_value"+index].value;
}
document.forms[0]["passedITems"] = arr.join(",");
docmentt.forms[0].submit();
on your server side, read "passedItems", and split by ",", you get an array of "name=value", split again on "=" you get a sub array of name, and value