0

for example I have an array like this:

var t = ko.observableArray([
  {"FoodName":"Rice","FoodOften":"2"},
  {"FoodName":"Apple","FoodOften":"3"}
]);   

How can I add an static item to all of them like below in a smart way?

[
  {"Student":"1","FoodName":"Rice","FoodOften":"2"},    
  {"Student":"1","FoodName":"Apple","FoodOften":"3"}      
]

I know I can loop t().length to add t()[n].Student="1" but just wondering is there any smart way for knockout?

1 Answer 1

1

Every variation on answering this question is going to be some form of 'iterate over the array and add the value to each object'. A few:

t.forEach(function(entry) {
    entry.Student = 1;
});

var newT = t.map(function(entry) {
    entry.Student = 1;
    return entry;
});

for (var i = 0; i++; i< t.length) {
    t[i].Student = 1;
}

Incidentally, at least in Chrome, jsperf says the first is the most efficient of those three.

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.