How would I check in my array of objects, if a specific item exists (in my case MachineId with id 2)?
[{"MachineID":"1","SiteID":"20"},{"MachineID":"2","SiteID":"20"},{"MachineID":"3","SiteID":"20"},{"MachineID":"4","SiteID":"20"}]
I tried this:
if (index instanceof machineIds.MachineID) {
alert('value is Array!');
} else {
alert('Not an array');
}
In cross browser way you may use jQuery.grep() method for it:
var item = $.grep(machineIds, function(item) {
return item.MachineID == index;
});
if (item.length) {
alert("value is Array!");
}
The simplest to understand solution is to loop over the array, and check each one.
var match;
for (var i = 0; i < yourArray.length; i++) {
if (yourArray[i].MachineId == 2)
match = yourArray[i];
}
Note if there is more than one matching item, this will return the last one. You can also dress this up in a function.
function findByMachineId(ary, value) {
var match;
for (var i = 0; i < ary.length; i++) {
if (ary[i].MachineId == value)
match = ary[i];
}
return match;
}
There are many standard solution, you don't need third party libraries or loop iteratively.
Array some method - since JavaScript 1.6.
Array find method - since ES6
Array findIndex method - since ES6
For example, using some();
var yourArray = [{"MachineID":"1","SiteID":"20"},{"MachineID":"2","SiteID":"20"},{"MachineID":"3","SiteID":"20"},{"MachineID":"4","SiteID":"20"}];
var params = {searchedID: "2", elementFound: null};
var isCorrectMachineID = function(element) {
if (element.MachineID == this.searchedID);
return (this.elementFound = element);
return false;
};
var isFound = yourArray.some(isCorrectMachineID, params)
Array some method accepts two parameters:
callback - Function to test for each element.
thisObject - Object to use as this when executing callback.
Callback function is not coupled with the iteration code and, using thisObject parameter, you can even return to the caller the element found or more data.
If such an element is found, some immediately returns true
http://jsfiddle.net/gu8Wq/1/
You could use this condition:
if (arr.filter(function(v){return this.MachineID == 2;}).length > 0)
Old question at this point, but here's an ES6 solution that uses Array.find:
let machine2 = machines.find((machine) => machine.id === '2');
if (machine2) {
// ...
}
var item = [{"MachineID":"1","SiteID":"20"},{"MachineID":"2","SiteID":"20"},{"MachineID":"3","SiteID":"20"},{"MachineID":"4","SiteID":"20"}];
var newItem = item.filter(function(i) {
return i.MachineID == 2; //it will return an object where MachineID matches with 2
});
console.log(newItem); // will print [{"MachineID":"2","SiteID":"20"}]
Related
I have an object which contains alot of keys and values. I can get any value using the index. But I dont have the full index, I have a part of it, would I be able to get the value based on a part of the index.
Example:
c = {'select':'MyValue',...}
I can get the value using indexing as shown below:
c['select'] = 'MyValue'
I tried to create this function which searches exact value:
function search(nameKey, c){
for (var i=0; i < c.length; i++) {
if (c[i].select === nameKey) {
return c[i];
}
}
}
c['select'] will return 'MyValue' but I need to do something like c['Sel'] or c['select'] or c['Select']or c['selected']to return the same 'MyValue'
Well the logic doesn't seem to be very clear and it's not quite relevant how it would be matching the key.
But This is a function that may help in the specific cases you showed:
function search(nameKey, obj) {
if (obj.hasOwnProperty(nameKey)) {
return obj[nameKey];
} else {
var res = Object.keys(obj).filter(function(k) {
return (k.toLowerCase().indexOf(nameKey.toLowerCase()) > -1) || (nameKey.toLowerCase().indexOf(k.toLowerCase()) > -1);
});
return res ? obj[res] : false;
}
}
Explanation:
First we use Object#hasOwnProperty() to check if the object has the searched name as key/property, we return it's value, this will avoid looping all the keys.
Otherwise we use Object.keys() to get the keys of the object.
Then we use Array#filter() method over the keys array to check if a relevant key exists we
return it's value, otherwise we return false.
Demo:
function search(nameKey, obj) {
if (obj.hasOwnProperty(nameKey)) {
return obj[nameKey];
} else {
var res = Object.keys(obj).filter(function(k) {
return (k.toLowerCase().indexOf(nameKey.toLowerCase()) > -1) || (nameKey.toLowerCase().indexOf(k.toLowerCase()) > -1);
});
return res ? obj[res] : false;
}
}
var c = {
'select': 'MyValue'
};
console.log(search("Sel", c));
Here's an one liner (!):
Assuming your array is in data and the partial index value is in selector:
const result = Object.keys(data).filter(k => k.toLowerCase().indexOf(selector.toLowerCase()) != -1).map(k => data[k]);
The above code returns an Array (coz, there may be more than one match). If you just need a first element, just do result[0].
You can use Object.keys() to get an array of the property names.
Then find first match using Array#find() to get the key needed (if it exists)
const data = {
aaaa: 1,
bbbbbbb: 2,
cccc: 3
}
function search(nameKey, obj) {
nameKey = nameKey.toLowerCase();// normalize both to lowercase to make it case insensitive
const keys = Object.keys(obj);
const wantedKey = keys.find(key => key.toLowerCase().includes(nameKey));
return wantedKey ? obj[wantedKey] : false;
}
console.log('Term "a" value:', search('a',data))
console.log('Term "bb" value:', search('bb',data))
console.log('Term "X" value:', search('X',data))
Since search criteria is vague I simply found any match anywhere in the property name and didn't look past the first one found
Im trying to get indexOf of a object after its pushed inside a array.
This is not returning the same value back as i do indexOf whenever objext is allready in the array.
SCENARIO
var arr = [];
setInterval(function() {
var path = { one: "f00"};
if (typeof path !== "undefined") {
if (arr.indexOf(path) === -1) {
console.log("Not Exists!!")
arr.push(path)
} else {
console.log("Exists!!")
}
}
console.log(arr)
}, 2000)
What is the different between the working of
The issue is that JavaScript doesn't do a deep compare of objects, so it doesn't recognize them as the same.
var a = { name: 'foo' }
var b = { name: 'foo' }
a === b // false
However, since you have access to the object before the insert, you can save a reference to it, and then search for that reference:
var arr = []
var obj = { path: 'foo' }
arr.push(obj)
arr.indexOf(obj) // 0
This is because indexOf uses the strict equality === comparison. So in this case, the references to obj and the object at arr[0] are the same.
Edit
Based on your changed question, here is a way to write your function to do what you want:
var arr = [];
function findAdnSet(obj) {
var index = arr.indexOf(obj);
if (index !== -1) {
return index;
} else {
arr.push(obj);
return arr.length - 1; // No reason to use indexOf here, you know the location since you pushed it, meaning it HAS to be the last element in the array
}
}
var path = { name: 'foo' };
findAndSet(path);
A more robust option than using indexOf since your function might not always have a good reference available is to use find/findIndex:
var arr = [];
function findAndSet(obj) {
var index = arr.findIndex(function(item) {
if (item.name === 'foo') {
return true;
}
});
if (index) { // findIndex returns `undefined` if nothing is found, not -1
return index;
} else {
arr.push(obj);
return arr.length - 1;
}
}
// You don't need a reference anymore since our method is doing a "deep" compare of the objects
findAndSet({ name: 'foo' });
The first time you do indexOf you push and search for the object 'path' so it is found. The second time you create an object and add push it to the array, and then search for another new object (which happens to have the same values), but since it is not the same object that you pushed it is not found.
I'm working to convert my code into plain JS, it's really hard. I need a function to get the real scroll container and the one I have goes like this, using .map().
//get true container for scroll events
function getScrollContainer(c) {
return $(c).map(function() {
var cnt = this,
isWin = !cnt.nodeName || $.inArray( cnt.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1;
if (!isWin) return cnt;
var doc = (cnt.contentWindow || cnt).document || cnt.ownerDocument || cnt;
return /webkit/i.test(navigator.userAgent) || doc.compatMode == 'BackCompat' ?
doc.body :
doc.documentElement;
});
}
console.log(getScrollContainer(window));
is there a way to accomplish this?
Map is just a fancy way to say "apply this function to every element in the list" so it could be easily implemented in a for loop.
Something like this: (Not perfect or tested, but should give you an idea)
function getScrollContainer(c) {
c = Object.prototype.toString.call( c ) === '[object Array] ? c : [c];
for (var i = 0; i < c.length; i++) {
var cnt = c[i],
isWin = !cnt.nodeName || indexOf(cnt.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1;
if (!isWin) return cnt;
var doc = (cnt.contentWindow || cnt).document || cnt.ownerDocument || cnt;
return /webkit/i.test(navigator.userAgent) || doc.compatMode == 'BackCompat' ?
doc.body :
doc.documentElement;
}
}
Based on the code that you have posted you don't need to use the map method. Your function accepts just one parameter so you can just remove the var cnt = this, line and use the c parameter. Now your function instead of returning a jQuery-wrapped array with length of 1, returns a HTMLElement object.
If you want to pass an array to the function you can use Array.prototype.map method:
function getScrollContainer(c) {
return c.map(function(value, index, arr) {
// ...
});
}
console.log(getScrollConainer([window, 'foo']));
And for replacing the jQuery $.inArray utility function you can use the Array.prototype.indexOf method:
['iframe','#document','html','body'].indexOf(cnt.nodeName.toLowerCase()) != -1
Note that IE8 and below do no support the Array map and indexOf methods. If you want to support those browsers you can use a polyfill. MDN suggests this polyfill for Array.prototype.indexOf.
While the answers above will work in your case, they will not in every case. jQuery's map creates a new array and returns that array after applying the function to every item in the array.
the prototype map function does not create a new array and instead simply applies the function to each item.
this sometime will produce the same result and others will produce different results.
You will get the same result for this example:
$.map([1,2,3], function(i){ return i+1; });
=> [2,3,4]
[1,2,3].map(function(i){ return i+1; });
=> [2,3,4]
However the below example will provide a different result:
$.map([1,2,3], function(i){ if(i > 1){ return i; } });
=> [2,3]
[1,2,3].map(function(i){ if(i > 1){ return i; } });
=> [undefined,2,3]
In case anyone is interested, you can use if statements inside .map() if you create a new function for the Array prototype:
Array.prototype.custom_Map = function(x) {
arr = [];
for (var i = 0; i < this.length; i++)
var _this = (x(this[i], i, this));
if(_this !== null) {
arr.push(_this);
return arr;
};
You can use it the following way:
x.custom_Map(function(a){ if(a>0) {return true;}});
I have a dictionary:
[ object , object, object, object, object ]
object contains: id and name.
I have an Id ('123456') and I want to get the object with this id.
Is there another solution how can I do it without for loop on the objects?
any help appreciated!
Hate loops, then go for recursion, i just assumed that you are having that array in a variable called as xArr
var xObj = check(0,"123456");
function check(cnt,id) {
if(xArr[cnt].id === id)
{
return xArr[cnt];
}
else if(cnt === xArr.length - 1) {
return null;
}
else {
cnt += 1;
return check(cnt, id);
}
}
That's an array, you could use jQuery.grep to get the elements with id "123456".
var result = $.grep(arr, function(obj) {
return obj.id === '123456';
});
Array also provide an .filter method (need a polyfill for browsers not support it):
var result = arr.filter(function(obj) {
return obj.id === '123456';
});
If you want to use a vanilla JS method, you can use filter. This pretty much does the same as $.grep.
var result = arr.filter(function (obj) {
return obj.id === '123456';
});
I have an array of objects. Each object has, among others, an ID attribute. I want to find the index in the array of the object with a specific ID. Is there any elegant and simple way to do this in jQuery?
See [`Array.filter`][1] to filter an array with a callback function. Each object in the array will be passed to the callback function one by one. The callback function must return `true` if the value is to be included, or false if not.
var matchingIDs = objects.filter(function(o) {
return o.ID == searchTerm;
});
All objects having the ID as searchTerm will be returned as an array to matchingIDs. Get the matching element from the first index (assuming ID is unique and there's only gonna be one)
matchingIDs[0];
[1]: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter
Update:
Checkout findIndex from ECMAScript 6.
items.findIndex(function(item) { item.property == valueToSearch; });
Since findIndex isn't available on most browsers yet, you could backfill it using this implementation:
if (!Array.prototype.findIndex) {
Array.prototype.findIndex = function(predicate) {
if (this == null) {
throw new TypeError('Array.prototype.findIndex called on null or undefined');
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var list = Object(this);
var length = list.length >>> 0;
var thisArg = arguments[1];
var value;
for (var i = 0; i < length; i++) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return i;
}
}
return -1;
};
}
In the case you should use for loop in javascript instead of using jQuery. See way 3 in http://net.tutsplus.com/tutorials/javascript-ajax/10-ways-to-instantly-increase-your-jquery-performance/
UPDATED: jQuery is written in javascript and it can not be faster than another code written also in javascript. jQuery is very good if you work with the DOM, but doesn't really help if you're working with simple javascript arrays or objects.
The code you're looking for can be something like this:
for (var i=0, l = ar.length; i<l; i++) {
if (ar[i].ID === specificID) {
// i is the index. You can use it here directly or make a break
// and use i after the loop (variables in javascript declared
// in a block can be used anywhere in the same function)
break;
}
}
if (i<l) {
// i is the index
}
Important that you should hold some simple javascript rules: Always declare local variables (don't forget var before variable declaration) and cache any properties or indexes that you use more than one time in a local variable (like ar.length above). (See for example http://wiki.forum.nokia.com/index.php/JavaScript_Performance_Best_Practices)
Not really elegant, but a cute trick:
var index = parseInt(
$.map(array, function(i, o) { return o.id === target ? i : ''; }).join('')
);
jQuery doesn't have a lot of functional constructs like that; the philosophy of the library is really focused on the job of DOM wrangling. They won't even add a .reduce() function because nobody can think of a reason it'd be useful to the core functionality.
The Underscore.js library has a lot of such facilities, and it "plays nice" with jQuery.
There are no built-in methods for this; the [].indexOf() method doesn't take a predicate, so you need something custom:
function indexOf(array, predicate)
{
for (var i = 0, n = array.length; i != n; ++i) {
if (predicate(array[i])) {
return i;
}
}
return -1;
}
var index = indexOf(arr, function(item) {
return item.ID == 'foo';
});
The function returns -1 if the predicate never yields a truthy value.
Update
There's Array.findIndex() that you could use now:
const arr = [{ID: 'bar'}, {ID: 'baz'}, {ID: 'foo'}];
const index = arr.findIndex(item => item.ID === 'foo');
console.log(index); // 2
Use jOrder. http://github.com/danstocker/jorder
Feed your array into a jOrder table, and add an index on the 'ID' field.
var table = jOrder(data)
.index('id', ['ID']);
Then, get the array index of an element by:
var arrayidx = table.index('id').lookup([{ ID: MyID }]);
If you want the entire row, then:
var filtered = table.where([{ ID: MyID }]);
Voila.