我在数组中有下面的对象
[
{
"event":"a",
"count":0
},
{
"event":"b",
"count":0
},
{
"event":"c",
"count":0
}
]
我需要检查count的所有值是否均为零。
我尝试了以下代码
Object.values(alarmTypeCount).every(count => count === 0)
每次都返回false
答案 0 :(得分:5)
您需要对对象进行解构以获得想要的属性。
var alarmTypeCount = [{ event: "a", count: 0 }, { event: "b", count: 0 }, { event: "c", count: 0 }],
allCountsZero = Object.values(alarmTypeCount).every(({ count }) => count === 0);
console.log(allCountsZero);
或者带对象的属性。
var alarmTypeCount = [{ event: "a", count: 0 }, { event: "b", count: 0 }, { event: "c", count: 0 }],
allCountsZero = Object.values(alarmTypeCount).every(o => o.count === 0);
console.log(allCountsZero);
答案 1 :(得分:2)
您需要解构“每个”函数的论点
lately_number.txt
答案 2 :(得分:2)
首先,数组上的Object.values()
是多余的,因为它只会为您提供数组中的元素数组(您的情况下为对象),这正是数组的意义。示例中的count
表示数组中的给定对象。您需要像这样访问对象的count
属性:
alarmTypeCount.every(obj => obj.count === 0)
或者,您可以通过销毁分配来做到这一点:
alarmTypeCount.every(({count}) => count === 0)
请参见以下示例:
let alarmTypeCount = [{"event":"a", "count":0}, {"event":"b", "count":0}, {"event":"c", "count":0}];
console.log(alarmTypeCount.every(obj => obj.count === 0));
答案 3 :(得分:1)
使用public void Pickdateheatdryopen(View view) {
String oldDate = "2017-01-29";
System.out.println("Date before Addition: "+oldDate);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calender = Calendar.getInstance();
try{
calender.setTime(sdf.parse(oldDate));
}catch(ParseException e){
e.printStackTrace();
}
calender.add(Calendar.DATE,21);
final int year = calender.get ( Calendar.YEAR );
final int month = calender.get ( Calendar.MONTH );
final int day = calender.get ( Calendar.DAY_OF_MONTH );
datePickerDialog = new DatePickerDialog ( CowActivity.this, new DatePickerDialog.OnDateSetListener () {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
inputheatdry.setText ( (dayOfMonth) + "/" + (month+1 ) + "/" + (year) );
// read1 ();
}
}, year, month, day );
datePickerDialog.show ();
}
方法有多个选项,下面是一个摘要,其中包括其他人提到的一些选项:
使用every
Array.prototype
使用some
const isAllZeros = alarmTypeCount.every(a => a.count === 0)
使用find
const isAllZeros = !alarmTypeCount.some(a => a.count !== 0)
const isAllZeros = !alarmTypeCount.find(a => a.count !== 0)
使用filter
const isAllZeros = alarmTypeCount.findIndex(a => a.count !== 0) === -1
答案 4 :(得分:0)
您可以使用filter
方法进行检查
let array = [
{
"event":"a",
"count":0
},
{
"event":"b",
"count":0
},
{
"event":"c",
"count":0
}
]
let newArray = array.filter((obj)=>{
return obj.count > 0;
});
if(newArray.length == 0){
console.log("All the elements are zero");
}else{
console.log(newArray.length + " elements are non zero");
}