JS Object Array删除最后一个空元素

时间:2017-01-20 16:13:56

标签: javascript object

我有那个javascript对象:

MyObject = [
   {
     "name" : "aaa",
     "firstname" : "aaaaa"
   },
   {
     "name" : "bbb",
     "firstname" : "bbbb"
   },
   {
     "name" : "cccc",
     "firstname" : "" <--------- firstname is empty, but the element is not in the last
   },
   {
     "name" : "ddd",
     "firstname" : "dddd"
   },
   {
     "name" : "eeee",
     "firstname" : ""  <--------- firstname is empty
   },
   {
     "name" : "fffff",
     "firstname" : ""  <--------- firstname is empty
   },
]

我想删除“firstname”为空的最新行 ...(一种修剪)...我不想删除所有“firstname”为空的行。但只是谁在latestes线。 (位于底部)

所以,结果将是:

MyObject = [
   {
     "name" : "aaa",
     "firstname" : "aaaaa"
   },
   {
     "name" : "bbb",
     "firstname" : "bbbb"
   },
   {
     "name" : "cccc",
     "firstname" : ""
   },
   {
     "name" : "ddd",
     "firstname" : "dddd"
   }
]

谢谢

2 个答案:

答案 0 :(得分:1)

只要firstname为空

,就可以弹出数组的末尾

var MyObject = [{
    "name": "aaa",
    "firstname": "aaaaa"
}, {
    "name": "bbb",
    "firstname": "bbbb"
}, {
    "name": "cccc",
    "firstname": ""
}, {
    "name": "ddd",
    "firstname": "dddd"
}, {
    "name": "eeee",
    "firstname": ""
}, {
    "name": "fffff",
    "firstname": ""
}];

for (var i=MyObject.length;i--;) if (MyObject[i].firstname==="") MyObject.pop(); else break;

console.log(MyObject)
.as-console-wrapper {max-height: 100%!important; top: 0!important;}

答案 1 :(得分:0)

试试这个:

&#13;
&#13;
var MyObject = [
   {
     "name" : "aaa",
     "firstname" : "aaaaa"
   },
   {
     "name" : "bbb",
     "firstname" : "bbbb"
   },
   {
     "name" : "cccc",
     "firstname" : ""
   },
   {
     "name" : "ddd",
     "firstname" : "dddd"
   },
   {
     "name" : "eeee",
     "firstname" : ""
   },
   {
     "name" : "fffff",
     "firstname" : ""
   }
];
var i = MyObject.length;
while(true) {
  if (!MyObject[--i].firstname) {
    MyObject.pop();
  } else {
    break;
  }
}
console.log(MyObject);
&#13;
&#13;
&#13;