简体   繁体   English

JS对象数组删除最后一个空元素

[英]JS Object Array Remove last empty element

I have that 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
   },
]

I want to delete the lastest lines that have "firstname" empty ... (a sort of trim) ... i dont want to remove all lines that have "firstname" empty... but just who are in the latestes lines. 我想删除具有“ firstname”为空的最新行 ...(一种修整)...我不想删除具有“ firstname”为空的所有行...,而是那些最新行中的人。 (that are in the bottom) (在底部)

So, the result will be : 因此,结果将是:

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

Thank you 谢谢

You can pop of at the end of the array as long as the firstname is empty 您可以在数组末尾弹出,只要名字为空

 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;} 

Try this: 尝试这个:

 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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM