Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip object items if the value is null

Tags:

vue.js

I have a nested for ... in loop in vue js. What I'm trying to to is to skip elements if the value of the element is null. Here is the html code:

<ul>     <li v-for="item in items" track-by="id">         <ol>             <li v-for="child in item.children" track-by="id"></li>         </ol>     </li> </ul> 

null elements may be present in both item and item.children objects.

For example:

var data = {    1: {       id: 1,       title: "This should be rendered",       children: {           100: {               id: 100,               subtitle: "I am a child"           },           101: null       }    },    2: null,    3: {        id: 3,        title: "Should should be rendered as well",        children: {}    } }; 

With this data data[1].children[101] should not be rendered and if data[1].children[100] becomes null later it should be omitted from the list.

P.S. I know this is probably not the best way to represent data but I'm not responsible for that :)

like image 949
King Julien Avatar asked Mar 24 '16 16:03

King Julien


People also ask

Can objects accept null?

No , null is not an object.It is a reference type and its value does not refer to any object and so there is no representation of null in memory.

How do you ignore null fields in JSON response?

You can ignore null fields at the class level by using @JsonInclude(Include. NON_NULL) to only include non-null fields, thus excluding any attribute whose value is null. You can also use the same annotation at the field level to instruct Jackson to ignore that field while converting Java object to json if it's null.


Video Answer


1 Answers

Edit: Actually, a simple v-if might work:

<li v-for="item in items" v-if="item !== null" track-by="id"> 

Give it a try. If not, do this:

You can add a filter for that (in main.js before App instance):

Vue.filter('removeNullProps',function(object) {   // sorry for using lodash and ES2015 arrow functions :-P   return _.reject(object, (value) => value === null) }) 

then in the template:

<li v-for="item in items | removeNullProps" track-by="id">     <ol>         <li v-for="child in item.children | removeNullProps" track-by="id"></li>     </ol> </li> 
like image 149
Linus Borg Avatar answered Sep 17 '22 15:09

Linus Borg