Find an element exist in List using jQuery - javascript

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)

Related

Matching a string to an array

I need your your help,
For some strange reason, when my var str is set to "OTHER-REQUEST-ASFA" the matched key comes back as "ASF" as opposed to "ASFA"
How can I get the returned output key of "ASFA" when my str is "OTHER-REQUEST-ASFA"
function test() {
var str = "OTHER-REQUEST-ASFA"
var filenames = {
"OTHER-REQUEST-ASF": "ASF",
"OTHER-REQUEST-ASFA": "ASFA",
"OTHER-REQUEST-ASFB": "ASFB",
"OTHER-REQUEST-ASFC": "ASFC",
"OTHER-REQUEST-ASFE": "ASFE"
}
for (var key in filenames) {
if (str.indexOf(key) != -1) { alert(filenames[key]) }
}
}
You could switch from
str.indexOf(key)
to
key.indexOf(str)
function test() {
var str = "OTHER-REQUEST-ASFA",
filenames = {
"OTHER-REQUEST-ASF": "ASF",
"OTHER-REQUEST-ASFA": "ASFA",
"OTHER-REQUEST-ASFB": "ASFB",
"OTHER-REQUEST-ASFC": "ASFC",
"OTHER-REQUEST-ASFE": "ASFE"
},
key;
for (key in filenames) {
if (key.indexOf(str) != -1) {
console.log(filenames[key]);
}
}
}
test();
To answer why it's not working as you want...
You've got:
str.indexOf(key)
This checks for the first instance of key in str.
So in your loop, key first equals OTHER-REQUEST-ASF which is part of OTHER-REQUEST-ASFA, so the condition is true.
However, to do what you want to do, if you know the pattern is always going to be OTHER-REQUEST-XYZ, the easiest way is to use split():
str.split('-')[2]
will always return the last section after the last -
cause "OTHER-REQUEST-ASFA".indexOf("OTHER-REQUEST-ASF") will not return -1, so it will show "ASF"
You can also use static method Object.keys() to abtain array of keys
var test = () =>{
var str = "OTHER-REQUEST-ASFA"
var filenames = {
"OTHER-REQUEST-ASF": "ASF",
"OTHER-REQUEST-ASFA": "ASFA",
"OTHER-REQUEST-ASFB": "ASFB",
"OTHER-REQUEST-ASFC": "ASFC",
"OTHER-REQUEST-ASFE": "ASFE"
}
Object.keys(filenames).forEach(x => {
if ( x.indexOf(str) !== -1)
console.log(filenames[str]);
});
}
test();

Use underscore to find a value by key

I have a string that I need to search for within a json object and return back a specific hash number from that found value. I got it to work without underscore, but it's poorly optimized. What I need to do is stop the loop as soon as the fileToSearch string is found.
For example, I have a json object here:
var json = {
"images/mike.jpg" : "images/mike.12345.jpg",
"images/joe.jpg" : "images/joe.axcvas.jpg",
"images/mary.jpg" : "images/mary.mndfkndf.jpg",
"images/jane.jpg" : "images/jane.dfad34.jpg",
};
And I have a variable fileToSearch that I need to look for in the above object.
var fileToSearch = "joe.jpg";
What should get outputted is the hash value in images/joe.axcvas.jpg, so axcvas.
Without underscore:
var hash;
for (var key in json) {
var index = key.indexOf(fileToSearch);
if (index !== -1) {
hash = json[key].split('.')[1];
}
}
console.log(hash); //axcvas
How can I optimize/achieve this with Underscore?
You can use _.findKey in such way:
var key = _.findKey(json, function(value, key) {
return key.indexOf(fileToSearch) >= 0;
});
var hash = key? json[key].split('.')[1] : undefined;
Note that this method is available since v1.8.0.
You can break the loop when you find the element
var hash;
for (var key in json) {
var index = key.indexOf(fileToSearch);
if (index !== -1) {
hash = json[key].split('.')[1];
break;
}
}
console.log(hash);

jQuery $.inArray() always return -1 with an array of object

I have an array of object, that contain key value pair of columnNames.
when i check if a particular columnName exists it alwayz returns -1
Here is an sample http://jsfiddle.net/trLkt/6/, Help will b appriciated
You're searching for string values in the columnModel array, but you're storing objects in it (columnModel.push({'colName': $(this).text()});). $.inArray() cannot decide by itself to compare against the colName property of each array element, it simply compares the value you're searching for against each array element.
Two things you can do:
Add strings to the array instead of objects using .push (as suggested by #lanzz), then $.inArray will work as you expect.
Alternatively, if you do need to store objects within the array (if for example you need to have multiple properties within each object) you would need to iterate over each object and see if the colName already exists:
var colExists = false;
var text = $(this).text();
$.each(columnModel, function(k, v) {
if(text == v['colName']) {
colExists = true;
}
});
Then change your check from if(colExists === -1) to if(!colExists).
Example
$(function () {
$('#ddlMain').change(function (event) {
$('option:selected', $(this)).each(function () {
var colExists = false;
var text = $(this).text();
$.each(columnModel, function(k, v) {
if(text == v['colName']) {
colExists = true;
}
});
if(!colExists) {
columnModel.push({'colName': $(this).text()});
alert($(this).text() + ' added to columnModel');
}
});
});
});

jQuery inArray with Hashtable

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;
}

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