是否有一种快速稳定的方法来从json Doc数组中删除所有键值对。在我的情况下,我从数据库返回的数据包含更多字段,然后我想向用户显示,因此我想查询我的数据库,并在将json返回给客户端之前查看他应该获得什么密钥。 在此示例中,数据具有3个键,FirstName,LastName和dob我将如何删除json中的所有dob键和值,如果我必须删除多个键值对,那么当您这样做时会有所不同吗?
{
"result":[
{
"FirstName": "Test1",
"LastName": "User",
"dob": "01/01/2011"
},
{
"FirstName": "user",
"LastName": "user",
"dob": "01/01/2017"
},
{
"FirstName": "Ropbert",
"LastName": "Jones",
"dob": "01/01/2001"
},
{
"FirstName": "hitesh",
"LastName": "prajapti",
"dob": "01/01/2010"
}
] }
答案 0 :(得分:1)
在遍历数据时,可以在obj上使用delete运算符。
let data = {
"result": [{
"FirstName": "Test1",
"LastName": "User",
"dob": "01/01/2011"
},
{
"FirstName": "user",
"LastName": "user",
"dob": "01/01/2017"
},
{
"FirstName": "Ropbert",
"LastName": "Jones",
"dob": "01/01/2001"
},
{
"FirstName": "hitesh",
"LastName": "prajapti",
"dob": "01/01/2010"
}
]
}
// @param keys: an array of keys to remove
function removeKeyValue(obj, keys) {
obj.forEach(currObj => {
keys.forEach(key => {
delete currObj[key];
});
});
}
removeKeyValue(data.result, ["dob", "LastName"]);
console.log(data.result);