Knockout : Push value in ko observable array with dynamic key

五迷三道 提交于 2019-12-11 15:35:58

问题


I want to add push value in array with dynamic key. I use this below code :

this.customOptionVal.push({name:value});

this.customOptionVal is ko.observableArray()

Output of the above code is :

0: {name: "stack"}

I want to get output like this :

mykey: {name: "stack"}

How to do this?


回答1:


If you can use a simple observable and not an observableArray (because arrays will always use indices and not custom keys), you can set that customOptionVal is an observable object: customOptionVal = ko.observable({})

Now you can access the object inside the observable with customOptionVal(), then you can add your key in this object, something like: customOptionVal()[yourKeyHere] = {name: "stack"}.

See below for a better example

var customOptionVal = ko.observable({});
customOptionVal()['myKey'] = {name:"stack"};

console.log(customOptionVal())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>


来源:https://stackoverflow.com/questions/54307799/knockout-push-value-in-ko-observable-array-with-dynamic-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!