1

How could I replace a observable array's content by storing it in another variable , say for example:

I have an observable array: var list = self.StateList();

And I want to do like this:

var cities = self.CityList();
//console.log(cities);
 var oldLocation = ko.utils.arrayFirst(cities, function (item) {
     return item.CityId == args.CityId;

 });

 cities.replace(oldLocation, args);

But it is showing error cities has no method replace,

UPDATE I tried with this anwser , it some how helped me I used observable slice method , it helped some how:

   var cities = self.CityList();
   var observble = ko.observable();
   observble(cities.slice(0));

So my all cities observable will be copied into a brand new observable

Now i can do what ever i want as it is same observable array of my cities. Somebody can think like why to convert observable array to variable and again converting it to observable array. I have a requirement to send my observable array to a function. If there is any other better solution please post it over here.

1 Answer 1

1

Please try this

// The observable array
this.CityList = ko.observableArray([{CityId :1 }, {CityId :2 } ,{CityId :3 }]);

// observable array stored in variable. The brackets should not be used if you 
// want to treat the cities variable as an observable array
 var cities = this.CityList;

 // Find a city with id 1.
 var oldLocation = ko.utils.arrayFirst(cities(), function (item) {
     return item.CityId == 1;

 });

console.log(oldLocation);

// Replace the city with id 5
cities.replace(oldLocation , {CityId :5 });

// The values in both arrays will get modified
console.log(cities()[0]);
console.log(this.CityList()[0]);
Sign up to request clarification or add additional context in comments.

2 Comments

it is not taking cities() as a argument in ko.utill.arrayFirst
when we do var cities = this.CityList; the array in the cities variable can be accessed by cities(). i.e value in the observable array.

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.