0

friends. I have the following issue. I have two observable arrays.

self.NamesArray= ko.observableArray([{"name: John"}, {"name: Mario"}]);

and

 self.ValueArray = ko.observable([]);

I would like to loop through the NamesArray and add only the name values to the ValueArray.

So the output ValueArray should contain the following elements in the end:

{John, Mario}

How can this happen? I am very new to JS and I am just researching the Knockout library. Any help with working example will be greatly appreciated. Thanks.

Fiddle: http://jsfiddle.net/PsyComa/RfWVP/

1 Answer 1

1

This really depends on your intention behind doing this.

If you want do to this just once, simply iterate over the first array:

// Load current values of the observables
var n = self.NamesArray(), v = self.ValueArray();

// Push all names from n to v
for (var i = 0; i < n.length; i++) {
    v.push( n[i].name );
}

// Update the "values" observable
self.ValueArray(v);

The downside with this is that "ValueArray" does not get updated whenever "NamesArray" changes. If you want "ValueArray" to be an array containing all names that can be found in "NamesArray" (and only those!), you can use a computed observable instead:

self.ValueArray = ko.computed(function() {
    var n = self.NamesArray(), v = [];
    // ...same for loop as above...
    return v;
});
Sign up to request clarification or add additional context in comments.

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.