我有一个包含对象的数组。对象具有属性名称。 我想要属性等于bart的对象的索引。我怎样才能找到该对象的索引?
答案 0 :(得分:1)
var data = [{ name: 'bart' }, { name: 'baz' }];
function getPropIndexByName(data, prop, str){
var ret = []; //updated to handle multiple indexes
$.each(data, function(k, v){
if(v[prop] === str)
ret.push(k);
});
return ret.length ? ret : null;
}
var result = getPropIndexByName(data, //data source
'name', //property name
'bart'); //property value
console.log(result);
答案 1 :(得分:0)
这样的事情:
for (var key in myobject)
{
console.log(key);
}
答案 2 :(得分:0)
var matches = jQuery.grep(array, function() {
// this is a reference to the element in the array
// you can do any test on it you want
// return true if you want it to be in the resulting matches array
// return false if you don't want it to be in the resulting matches array
// for example: to find objects with the Amount property set to a certain value
return(this.Amount === 100);
});
答案 3 :(得分:0)
如果你有:
var myArray = [{x: 1}, {x: 2}, {x: 3}];
获取我要做x === 2
的第一个对象的索引:
function indexOfFirstMatch (arr, condition) {
var i = 0;
for(;i < arr.length; i++) {
if(condition(arr[i])) {
return i;
}
}
return undefined;
}
var index = indexOfFirstMatch(myArray, function (item) { return item.x === 2; });
// => 1
如果你想成为一个真正的特立独行者,你可以扩展数组:
Array.prototype.indexOfFirstMatch = function indexOfFirstMatch (condition) {
var i = 0;
for(;i < this.length; i++) {
if(condition(this[i])) {
return i;
}
}
return undefined;
}
var index = myArray.indexOfFirstMatch(function (item) { return item.x === 2; });
// => 1
答案 4 :(得分:0)
如果它们实际上是单个元素下的HTML元素,那么
index = $('#parentobject').index('[property="bart"]')