Farhad-Taran
Farhad-Taran

Reputation: 6512

filter object and assign property values to array?

I have a ko object which has some properties. I only need the value of the ItemName property.

is it possible to filter this object and get the ItemName Property value and push it into an array.

items":[{"ItemID":1,"ItemName":"Asia","ItemLevel":0,"ItemParentID":0},
        {"ItemID":2,"ItemName":"Europe","ItemLevel":1,"ItemParentID":0},
        {"ItemID":3,"ItemName":"Africa","ItemLevel":2,"ItemParentID":0}]

so that we end up with the following:

array[0] = "Asia"
array[1] = "Europe"
array[2] = "Africa"

ko.utils.arrayFilter(items(), function(item) {
            return item.ItemName();
        });

Upvotes: 0

Views: 88

Answers (3)

Artem Vyshniakov
Artem Vyshniakov

Reputation: 16465

You wrote almost right code. Just replace arrayFilter with arrayMap:

ko.utils.arrayMap(items(), function(item) {
            return item.ItemName();
        });

Upvotes: 0

Anders
Anders

Reputation: 17564

Use arrayMap

items":[{"ItemID":1,"ItemName":"Asia","ItemLevel":0,"ItemParentID":0},
        {"ItemID":2,"ItemName":"Europe","ItemLevel":1,"ItemParentID":0},
        {"ItemID":3,"ItemName":"Africa","ItemLevel":2,"ItemParentID":0}]

var array = ko.utils.arrayMap(items, function(item) {
    return item.ItemName;
});

Upvotes: 2

Paul Manzotti
Paul Manzotti

Reputation: 5147

You could use the mapping plugin with an include mapping to only copy over the field you want:

var mapping = {
    'include': ["ItemName""]
}
var viewModel = ko.mapping.fromJS(items, mapping);

Upvotes: 1

Related Questions