del*_*ano 3 javascript arrays object splice
所以我有一个对象数组,我想在它为空时切片对象的属性.
例如:
var quotes = [
{
quote: "Bolshevism is not a policy; it is a disease. It is not a creed; it is a pestilence.",
source: "Winston Churchill",
citation: "",
year: "29 May 1919",
place: ""
},
{
quote: "Learn while you live",
source: "",
citation: "X",
year: "1950",
place: ""
}];
Run Code Online (Sandbox Code Playgroud)
我有一个对象列表,对象名称随机为空.
我想打印到页面只有非空的属性.
所以我试图遍历对象以找到indexOf()空属性并拼接它:
function findEmptyProp(quotes) {
for (prop in quotes) {
if(quotes[i].children === '') {
return indexOf(quotes[i]);
quotes.splice(i, 1);
}}}
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助
splice用于数组,但是当你处理对象时,你必须使用delete.
你可以尝试这样的事情:
var quotes = [{
quote: "Bolshevism is not a policy; it is a disease. It is not a creed; it is a pestilence.",
source: "Wyston Churchill",
citation: "",
year: "29 May 1919",
place: ""
}, {
quote: "Learn while you live",
source: "",
citation: "X",
year: "1950",
place: ""
}];
quotes.forEach(function(o){
for (var k in o){
if(o.hasOwnProperty(k) && isEmpty(o[k])){
delete o[k];
}
}
});
function isEmpty(val){
return val === undefined ||
val === null ||
(typeof(val) === "object" && Object.keys(val).length === 0) ||
(typeof(val) === "string" && val.trim().length === 0)
}
console.log(quotes)Run Code Online (Sandbox Code Playgroud)
正如deceze评论的那样,我已经为其他可以认为值为空的情况添加了处理.您还应该检查hasOwnProperty更新自身的属性.