[英]JS or jQuery how to delete key-value pair
Using JS or jQuery how to delete the key-value pair which the value is of type “ Null
” & ""
. 使用JS或jQuery如何删除值类型为“
Null
”和""
的键-值对。 eg before: 例如之前:
Object {style: "fruit", origin: "Thailand", day: "18d", color: "", weight: null}
alter: 改变:
Object {style: "fruit", origin: "Thailand", day: "18d"}
There are two parts to this: 这有两个部分:
Loop through the object's properties 遍历对象的属性
Remove a property from an object 从对象中删除属性
There are lots of ways to do the first, covered by this question's answers . 这个问题的答案涵盖了很多方法。 Assuming you only care about "own" (non-inherited) properties, I'd probably use
Object.keys
to get an array of property names and then loop that. 假设您只在乎“自己的”(非继承)属性,我可能会使用
Object.keys
来获取属性名称数组,然后对其进行循环。
The second is done with the delete
operator. 第二个是用
delete
运算符完成的。
So: 所以:
Object.keys(theObject).forEach(function(key) {
var value = theObject[key];
if (value === "" || value === null) {
delete theObject[key];
}
});
Live Example: 现场示例:
var theObject = { style: "fruit", origin: "Thailand", day: "18d", color: "", weight: null }; console.log("Before:", JSON.stringify(theObject, null, 2)); Object.keys(theObject).forEach(function(key) { var value = theObject[key]; if (value === "" || value === null) { delete theObject[key]; } }); console.log("After:", JSON.stringify(theObject, null, 2));
You can use for..in
to go through the loop to find which key has null
or ""
. 您可以使用
for..in
循环查找哪个键具有null
或""
。
Then use delete
to delete the key 然后使用
delete
删除密钥
var myObj = {
style: "fruit",
origin: "Thailand",
day: "18d",
color: "",
weight: null
}
for(var keys in myObj){
if(myObj[keys] ===null || myObj[keys] === ""){
delete myObj[keys]
}
}
console.log(myObj)
An easy solution by iterating threw the keys of your object and pushing properties matching in a resulting Array : 一个简单的解决方案,通过迭代抛出对象的键并在结果Array中推送匹配的属性:
var input = {style: "fruit", origin: "Thailand", day: "18d", color: "", weight: null};
var keys = Object.keys(input);
var result = {};
keys.forEach(key => {if (input[key] != null && input[key] != "") result[key] = input[key]});
console.log(result); // { style: 'fruit', origin: 'Thailand', day: '18d' }
var yourObj={style: "fruit", origin: "Thailand", day: "18d", color: "", weight: null}
for(var attr in yourObj){
if(!yourObj[attr]){
delete yourObj[attr]
}
}
It can be done using this code : 可以使用以下代码完成:
var map = {style: "fruit", origin: "Thailand", day: "18d", color: "", weight: null};
for (var i in map){
if(map[i]==null || map[i]==""){
delete(map[i]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.