TTT
TTT

Reputation: 113

Array to ignore of element is misisng

I have a list of rows to be added into array. If one of the element is missing then would need to ignore the record. Can someone please suggest how to do this in JS?

here is the data to be added into new array:

{"start":"20161229T160000","end":"20161229T164500","summary":"JJ1"},
{"start":"20170106T180000","end":"20170106T183000","rule":"FREQ=WEEKLY;BYDAY=FR","summary":"JJ2"},

I tried checking if (rrule !==null) or (rrule!='undefined')... nothing worked.. its keeps adding the row into array list..:(

I don't want to add first record into array..as rrule element is missing.

I'd appreciate any suggestions.

Upvotes: 0

Views: 42

Answers (2)

nnnnnn
nnnnnn

Reputation: 150040

Assuming your input is an array of objects, you can easily get an array of just the ones with the required properties by using the array .filter() method:

var input = [
     {"start":"20161229T160000","end":"20161229T164500","summary":"JJ1"},
     {"start":"20170106T180000","end":"20170106T183000","rule":"FREQ=WEEKLY;BYDAY=FR","summary":"JJ2"},
     {"start":"20161229T160000"},
     {"start":"20170205T180000","end":"20170206T183000","rule":"FREQ=WHATEVER;BYDAY=FR","summary":"XYZ"}
];

var output = input.filter(function(item) {
    return item.start != undefined
        && item.end != undefined
        && item.rule != undefined
        && item.summary != undefined;
});

console.log(output);

Your attempt if (rrule !==null) didn't work because a missing property is not null. Your attempt (rrule!='undefined') didn't work because it was testing for the string 'undefined', not the value undefined. Note that if it would be valid for a property to exist with the value undefined then you should test with item.hasOwnProperty('rule') rather than item.rule != undefined.

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234797

If item is one of the data objects, you can use hasOwnProperty() to test:

if (item.hasOwnProperty('rule')) {
    // add to array
}

That will work even if the value of rule is a "falsy" value (e.g., {...,"rule": 0,...}). If you want to exclude those as well, just use

if (item.rule) { ... }

Upvotes: 1

Related Questions