我希望能够从对象获取所有密钥。假设对象如下所示:
this.reservation = {
"Firstname" : "" ,
"Lastname" :"" ,
"Phone" : "",
"Email" : "",
"Date" : "yyyy-mm-dd hh:mm",
"Starthour" : "",
"Endhour" : "",
"Persons" : ""
}
如果我想能够检查是否所有按键'值为""
,当然除了Date
,我该怎么做呢?
我尝试过forEach
来获取密钥:
angular.forEach(this.reservation,
function(value, key) {
console.log(key);
});
但它不起作用。任何提示?
答案 0 :(得分:4)
试试这个,
Object.keys(reservation);
答案 1 :(得分:0)
您可以使用Object.keys和一些功能数组方法
var allEmptyExceptDate = Object.keys(this.reservation)
.filter(function(key) { return key !== 'Date'; }) // all except 'Date'
.every(function(key) { return !this.reservation[key] }) // are falsy (i.e. empty or undefined or null) - or you can use this.reservation[key] === '' for a more precise check
答案 2 :(得分:0)
对于对象,您可以使用 for in 循环
纯粹的javascript方式:
for(prop in this.reservation){
if(typeof this.reservation[prop] === "string"){
console.log(prop + 'value ' + "is a string");
}
}
Angular方式:
angular.forEach(this.reservation, function(value, key){
if(typeof value === "string"){
console.log(value + ' is of type string');
}
}