[英]Get JavaScript/angularJS object keys which contains NULL value
i have bind object 'p' with input fields using angularJS like this 我使用angularJS将对象'p'绑定到输入字段,就像这样
<input ng-model="p.p1" type="text" />
<input ng-model="p.p2" type="text" />
<input ng-model="p.p3" type="text" />
it seems like my object is like this when these inputs are empty: 当这些输入为空时,我的对象似乎是这样的:
var p =
{
"p1": null,
"p2": null,
"p3": null
};
I have tried 我努力了
Object.keys(p); // return [] (empty array)
Can any one tell me how I can get list of all keys contains in JavaScript object, including keys which contain null value as well ? 任何人都可以告诉我如何获取JavaScript对象中包含的所有键的列表,包括包含空值的键?
Iterate through for loop and get those keys which have null. 迭代for循环并获取那些具有null的键。
for(var key in p) {
if(p[key] == null) {
// do your stuff here!
}
}
why not use p.p1
? 为什么不使用
p.p1
? or else you can always use p['p1']
? 或者你总是可以使用
p['p1']
? if you don't define the key you want to access its free for the garbage collector to clean up. 如果你没有定义你想要访问它的密钥,垃圾收集器可以清理它。
You need to place a hook in your code that accesses that key directly, otherwise it will get cleaned up. 您需要在代码中放置一个直接访问该密钥的钩子,否则它将被清除。
Please try the below one. 请尝试下面的一个。 Object.keys in not supported in major browsers, So have a polyfill for that.
主要浏览器不支持Object.keys,因此有一个polyfill。
var p =
{
"p1": null,
"p2": null,
"p3": null
},key;
function getObjectKeys(p){
if(Object.keys){
key = Object.keys(p);
return key;
}else{
key = [];
for(var k in p){
key.push(k);
}
return key;
}
}
getObjectKeys(p);
Thank you all for your response, Actually the problem is not in JS code rather problem is with angularJS binding. 谢谢大家的回复,其实问题不在于JS代码而是问题在于angularJS绑定。 its not put any key+value in object when input field is empty.
当输入字段为空时,它不会在对象中放置任何键+值。 so that's why i got object like this
所以这就是我得到这样的对象的原因
var p = {}; // $scope.p is looks same as this
so i did not got any key from 所以我没有得到任何钥匙
Object.keys(p); // is also working fine.
other solutions posted by other guys are also work fine. 其他人发布的其他解决方案也可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.