我有对象数组:
[{name:'test', lastname: 'test', gender:'f'},{name:'test1', lastname: 'test1', gender:'m'},{name:'test2', lastname: 'test2', gender:'m'}]
如何使用genger从数组中获取第一个(也是唯一一个)对象:'m'?
答案 0 :(得分:2)
您可以使用find
var ar = [{name:'test', lastname: 'test', gender:'f'},{name:'test1', lastname: 'test1', gender:'m'},{name:'test2', lastname: 'test2', gender:'m'}];
var result = ar.find(function(e) {
return e.gender == 'm';
});
console.log(result)
答案 1 :(得分:0)
遍历数组并检查每次迭代中项是否有 mFromDate.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
final int actionPeformed = ev.getAction();
switch(actionPeformed){
case MotionEvent.ACTION_UP:{
mFromDate.setText("");
SetDateToDefault(1); //some method
Bundle args = new Bundle();
args.putInt("day", day1);
args.putInt("month", month1);
args.putInt("year", year1);
myDatePickerDialogFragment d1 = new myDatePickerDialogFragment();
d1.setArguments(args);
d1.setOnDateSetListener(datePickerListener1); //onDateSet Listener that is not included in this question
d1.show(getFragmentManager(), "days");
break;
}
return true;
}
});
。可能看起来像这样:
gender == 'm'
答案 2 :(得分:0)
您可以使用Array#find
如果数组中的元素满足提供的测试函数,则
function first_male(data) { for (var i = 0; i < data.length; i++) { if (data[i].gender == 'm') { return data[i]; } } } var data = [ {name:'test', lastname: 'test', gender:'f'}, {name:'test1', lastname: 'test1', gender:'m'}, {name:'test2', lastname: 'test2', gender:'m'} ]; first_male(data); // Object {name: "test1", lastname: "test1", gender: "m"}
方法在数组中返回find()
。否则返回undefined
。
value
&#13;
如果不可用,请使用polyfill。或
var array = [{name:'test', lastname: 'test', gender:'f'},{name:'test1', lastname: 'test1', gender:'m'},{name:'test2', lastname: 'test2', gender:'m'}];
console.log(array.find(a => a.gender ==='m'));
&#13;
答案 3 :(得分:0)
你只需循环你的阵列。这里有一个非常相似的主题:Find a value in an array of objects in Javascript 当找到相应的对象时,返回指令将跳出循环。