0

I have that javascript object :

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. (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

2
  • Can you show us the code you have so far? Commented Jan 20, 2017 at 16:17
  • How you define "lastest"? Commented Jan 20, 2017 at 16:18

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

It didn't remove item "name": "eeee"
@jcubic - I assumed "the lastest lines" was just the last item. I think I misunderstood that ?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.