raberana
raberana

Reputation: 11816

JavaScript map(), undefined property of object from the collection

I have a collection of filter objects which is this.selectedFilters.

I use the JS map method to select only the field property of the filter object.

 console.log(this.selectedFilters.map((val) => {
            console.log(val);
            console.log(val.field);
            console.log(val['field']);
            return val.field;
        }));

The result is:

enter image description here

Can somebody tell me why does val.field gives an undefined value? :(

PS: I used TypeScript

UPDATE:

I think I know why val was a string. Maybe it's because this.selectedFilters is a ng-model of a select HTML element (multiple enabled) with options having an object value. Maybe the option value was converted from an object to a json string when transferred to the this.selectedFilters model

Upvotes: 1

Views: 1572

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074949

The most likely answer is that val is a string containing the JSON you see in the console. If it were an object, the console output would look different.

It looks like you need to put a JSON.parse in there. You haven't shown the original TypeScript, but in the JavaScript it would look like this:

console.log(this.selectedFilters.map((val) => {
    val = JSON.parse(val);    // <====
    console.log(val);
    console.log(val.field);
    console.log(val['field']);
    return val.field;
}));

Upvotes: 1

Related Questions