转换可观察数组的形式并显示在 select 列表中

Converting the form of an observable array and displaying in select list

我有一个如下所示的可观察数组..

var myObservableArray = ko.observableArray(["Bungle","George","Zippy"]);

我希望将元素复制到另一个可观察数组中,但采用以下格式,其中类型始终未知..

var anotherObservableArray = ko.observableArray([
    { name: "Bungle", type: "Unknown" },
    { name: "George", type: "Unknown" },
    { name: "Zippy", type: "Unknown" }
]); 

如果原来的myObservableArray改变了,那么anotherObservableArray也需要改变。 真诚感谢任何帮助..

谢谢

您可以从原始数据创建视图模型然后使用它(jsfiddle):

var originalArray = ["Bungle","George","Zippy"];
function createItemModel(name) {
  var model = {
    name: ko.observable(name),
    type: ko.observable("Unknown"),
  }
  model.displayText = ko.computed(function() {
    return model.name() + '-' + model.type();
  });
  return model;
}
var myObservableArray = ko.observableArray(originalArray.map(createItemModel));

var viewModel = {
  myObservableArray: myObservableArray,
  selected: ko.observable()
};

ko.applyBindings(viewModel);

并在标记中使用它(来自你的第二个问题):

<select data-bind="options: myObservableArray,
                   optionsText: 'displayText',
                   value: selected"></select>

更新 1

已更新jsfiddle,更改了所选项目的类型。