Using jQuery's inArray method with a JavaScript associative array (or object)
It's possible that I'm not properly using jQuery's inArray()
function, but I have to construct an object that only has the indexes of two other JavaScript objects where the values match exactly:
var arr1 = {
a: "alfa",
b: "beta"};
var arr2 = {b: "beta"};
alert(jQuery.inArray(arr2, arr1));
Here, I expect to get an object that contains only:
{b: "beta"}
Similarly, if the arrays looked like this:
var arr1 = {
a: "alfa开发者_如何学Python",
b: "beta",
c: "test"};
var arr2 = {b: "beta",
c: "not the same value"};
I would still expect:
{b: "beta"}
Because the values in the c
index are not exactly the same.
Thanks in advance, ciao h.
Try this:
http://jsfiddle.net/treeface/u5xDz/1/
The idea here is that you loop over the arr1
object and see if a similar index exists in arr2, and if that index's value in arr1
matches that index's value in arr2
.
var arr1 = {
a: "alfa",
b: "beta"
},
arr2 = {b: "beta"},
combinedArr = {};
$.each(arr1, function(ind, el) {
if (typeof arr2[ind] !== 'undefined' && arr1[ind] === arr2[ind])
combinedArr[ind] = el;
});
console.log(combinedArr);
Default jQuery inArray function is not able to search in keys and values at the same time,
$.fn.array_search = function(what, where)
{
var Match = null;
if(where === undefined) var where = 'value';
$(this).each(function(key, value)
{
if(where == 'value')
{
if(what == value) Match = key;
}else
{
if(what == key) Match = value;
}
});
return (Match) ? Match : false;
}
usage:
$(array).array_search('Value to Search'); //default search in value
$(array).array_search('key to search', 'key'); //search in key
The variables that you have defined in your example are not arrays, but objects. Also, the first parameter to this function should be the value to search for. So, your code would need to be modified to be:
var arr1 = [
"alfa",
"beta" ];
var arr2 = [ "beta" ];
alert(jQuery.inArray(arr2[0], arr1));
I think what you may be after is more of an intersect of two objects/arrays. You could use the jQuery.map() or jQuery.grep() functions to write a specialized comparison function.
That is not an array. It is an object. Also [inArray][1] arguments are value, array
. So you could check for an object in an array like this:
var b = {b: "beta"}
var arr1 = [
{a: "alfa"},
b
];
alert(jQuery.inArray(b, arr1));
Arrays are declared with the square brackets
[value,value]
Objects are declared
{name: value, name: value }
[1]: http:// api.jquery.com/jQuery.inArray
精彩评论