jQuery inArray with Hashtable - javascript

I'm using a hash table and I'm trying to check for object existence. However I haven't been successful in figuring out how to do this. Could someone help guide me with this. Thanks.
current code.
When clientId equals field id and has item id return true, else add to saved_tokens.
var saved_tokens = {};
if ($.inArray(item.id, saved_tokens) == -1) {
saved_tokens.push[clientId] = item.id;
}

Don't use jQuery for that. Use pure JavaScript:
if (!saved_tokens.hasOwnProperty(clientId)) { // If clientId is not in the hash
saved_tokens[clientId] = item.id;
}
.push is an array method. A {} creates an object. Since this object is not an array, it doesn't have any array methods.

I personally use 'typeof'.
var saved_tokens = {};
if (typeof(saved_tokens[clientId]) == 'undefined') {
saved_tokens[clientId] = item.id;
}

Related

how to find specific objects and put them in an array in javascript

I have this result in my script
'[{"region":"NCA","depprt":"Havana, Cuba"},{"region":"NCA","depprt":"Havana, Cuba"},{"region":"NCA","depprt":"Montego Bay, Jamaica"},{"region":"NCA","depprt":"Montego Bay, Jamaica"}]'
this is the code to get it.
var jsonList = '#Html.Raw(Json.Encode(ViewBag.chk))'
var jsList = JSON.stringify(jsonList);
for jsList I got above result.now I want to get all depprt where region is equal to NCA.how can I do that.
You can use the .filter() method for this.
var ncaList = jsonList.filter(function(obj){ return obj.region == "NCA"; });
Very simple. Iterate over the jList array and see if the region property matches your condition or not then append the item to your filtered array.
var filtered = [];
jList.forEach(function(item) {
if(item.region == 'NCA') {
filtered.push(item);
}
});
Just iterate over it:
var filteredDepprts = [];
jsList.forEach(function(element){
if(element.region == 'NCA'){
filteredList.push(element.depprt); //or element if you want to push the full object
}
});
The JSON.stringify method converts a JavaScript value to a string.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
When you want to convert a JSON string to a JavaScript value, use JSON.parse
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
var jsonList = '#Html.Raw(Json.Encode(ViewBag.chk))'
var jsList = JSON.parse(jsonList);
Using single quotes around your #Html.Raw, creates a string and not a JavaScript value. The filter method does not work on strings
Eventually you could use Array.prototype.filter Filter out each element in array, that matches your criteria.
https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
Try map:
var obj= [];
for (i in jsonList) {
if (jsonList[i].region == "NCA") { obj.push(jsonList[i])};
}
https://jsfiddle.net/pd6hvn78/

Remove an object from an from an array by it's id (angular)

I'm trying to remove an object from an array by it's key/value of ID. I would normally just splice by index, however the index might be changing quite a bit because multiple users will be manipulating and updating the object so I want to hook onto something more concrete - aka the id. So I have a bit of logic to check if it still exists and if so remove it by it's ID. However I can't seem to get the syntax quite correct. I Am using underscore.js, I don't know if it's easier with/without it but it's worth mentioning.
Here's what I have -
$scope.toggleSelection = function(typeId,name,index){
//check if exists in array
check = $scope.multipleTypes.some( function( el ) {
return el.name === name;
});
//checked on/off actions
if($scope.items[index].checked == false || $scope.items[index].checked == undefined ){
//IS cecked
if(check){
//already exists, do nothing
}else{
$scope.multipleTypes.push({id:typeId, name:name, checked: true});
}
}else{
//IS not checked
if(check){
var list = _.filter($scope.multipleTypes, function(element){
return element.id != typeId;
}
$scope.multipleTypes = list;
}else{
//is not there, do nothing
}
}
};
So if it does exist and is checked off, it gets pushed. If it does exist and is unchecked, I want to remove it from $scope.multipleTypes by it's ID. I think I Am doing this wrong, all I want to do is remove that one object that has the matching ID from $scope.multipleTypes. Would appreciate any help. Thanks for reading!
If you can use UnderScore Js, You can do it very easily.
Here is an Example:
var someArray= [{Employee:'ved',id:20},
{Employee:"ved",age:25},
{Employee:"p",age:2}];
var a = _.findWhere(someArray,{id:25});//searching Element in Array
var b= _.indexOf(someArray,a);// getting index.
someArray.splice(b,1);// removing.
I normally find the object by id, then splice it out. Note that angularjs adds other properties to the object .
e.g
$scope.items = [......]
var findItemByID = function(id, items){
angular.forEach(items, function(item){
if(item.id === id){
return item;
}
})
return null;
}
var removeItemByID = function(id, items){
var item = findItemByID(id);
if(item){
items.splice(items.indexOf(item), 1);
}
}
//you can now do removeItemByID(id, $scope.items);
//I have not tested this code and it may have syntax errors. hope you get the idea.
Josh

Find an element exist in List using jQuery

I am pretty much working on the basics of jQuery, it could have done easily if it's in Java :P
var thread_list = [];
var feed_list = [];
$.each(json.messages, function(i, m) {
if (m.replied_to_id == "") {
alert(m.thread_id);
thread_list.push(m.thread_id);
}
});
$.each(json.references, function(i, r) {
if (r.id exists in threadList) { //how do I do this more effectively?
feed_list.push(r.url);
}
});
How to find an element exist in the List?
In a modern browser you could use the filter function on [].
var thread_list = [{id:1},{id:2},{id:3}];
var feed_list = [];
function exists(arr,prop,val){
var threads = arr.filter(function(e){
return e[prop] == val;
});
return !!threads.length;
}
alert(exists(thread_list, "id", 4)); //returns false
alert(exists(thread_list, "id", 2)); //returns true
JS FIDDLE: http://jsfiddle.net/7vTWj/
jQuery.inArray(r.id , threadList); //give 0 to any positive number if exist otherwise give -1
reference inarray
Try this:
$.each(json.references, function(i, r) {
if (threadlist.indexOf(r)!=-1) {
feed_list.push(r.url);
}
});
In java, actually you would create a JSONOBject for the original json and then get the json threadlist as a JSONArray and then convert it to an actual array to check it.
You can simply use
if ( $.inArray(r.id, threadList ) != 1 )
Use indexOf():
if (threadList.indexOf(r.id) != -1)
In case you're using an old browser that doesn't have indexOf(), you can use jQuery.inArray():
if ($.inArray(r.id, threadList) != -1)

Javascript: Removing an object from array by checking it's attribute

I might have written a pretty confusing title but my question is rather simple.
I'm looking for an efficient way to remove an item from an array. But my array is full objects that has been stringified (I'm writing my app on Node.js and I'm using JSON.stringify method). So my array is like this;
"{\"userID\":\"15\",
\"possibleFollowers\":[
{\"followerID\":\"201\",\"friends\":716},
{\"followerID\":\"202\",\"friends\":11887},
{\"followerID\":\"203\",\"friends\":11887}],
\"name\":\"John\",
\"lon\":\"Doe\"}"
My question is on Javascript(or Node). If I wanted to remove the from possibleFollowers with "followerID: 202", how would I be able to do that efficiently?
var string = "…";
var obj = JSON.parse(string);
obj.possibleFollowers = obj.possibleFollowers.filter(function(fol) {
return fol.followerID != "202";
});
string = JSON.stringify(obj);
var data = "{\"userID\":\"15\",\"possibleFollowers\":[{\"followerID\":\"201\",\"friends\":716},{\"followerID\":\"202\",\"friends\":11887},{\"followerID\":\"203\",\"friends\":11887}],\"name\":\"John\",\"lon\":\"Doe\"}";
var dataObject = JSON.parse(data);
dataObject.possibleFollowers = dataObject.possibleFollowers.filter(function(follower) {
return !(follower.followerID == "202");
});
data = JSON.stringify(dataObject);
In javascript, the splice method is used to delete an array element by index.
see :
http://www.roseindia.net/java/javascript-array/javascript-array-remove-index.shtml
try just to delete it by using "delete"
for (var i in possibleFollowers) {
if (possibleFollowers[i]['followerId'] == '216') {
delete possibleFollowers[i];
}
}

Dereferencing a variable to its value to use in another function javascript

function get_event_ids_from_dom()
{
var event_ids = {};
$.each(
$("td.ms-cal-defaultbgcolor a"),
function(index,value){
var str = new String(value);
var id = str.substring(str.indexOf('=')+1,str.length);
if(typeof(event_ids[id]) == "undefined")
{
event_ids[id] = this;
}
else
{
**event_ids.id.push(this);**
}
}
)
return event_ids;
}
In above javascript event_ids is a hashtable. I am trying to assign values to this hashtable.
A hashtable can be added with multiple values using "hashtable.key.push(value)". I am trying to do this using event_ids.id.push(this); in the above code.
I have declared "id" as a variable in the code. The problem is, I am not able to dereference variable "id" to its value.
Is this possible in jquery/javascript?
Example use of hashtable:
event_ids = {};
event_ids["1"]= 'John';
event_ids.1.push('Julie');
The above example would add john and julie to hash table.
Try this instead:
function get_event_ids_from_dom() {
var event_ids = {};
$.each(
$("td.ms-cal-defaultbgcolor a"),
function(index,value){
var str = value.toString();
var id = str.substring((str.indexOf('=') + 1), str.length);
if(typeof(event_ids[id]) == "undefined") {
event_ids[id] = [];
}
event_ids[id].push(this);
});
return event_ids;
}
Please, note that while object["id"] is the same as object.id, object[id] is not.
Nicola almost had it:
if(typeof(event_ids[id]) == "undefined") {
event_ids[id] = [];
}
event_ids[id].push(this);
Also please read the comment I left for your question.
In my opinion event_ids is an object (there are no hastables in javascript, just either indexed arrays or objects).
What you are tring to do is using push (an array method) on something that is not an array so i think you must change something:
you could try:
if(typeof(event_ids[id]) == "undefined")
{
event_ids[id] = [];// the property id of object event_ids is an array
event_ids[id].push(this);
}
else
{
event_ids[id].push(this);
}
It should work

Categories