问题描述
我想用动态键在数组中添加推入值.我使用以下代码:
I want to add push value in array with dynamic key. I use this below code :
this.customOptionVal.push({name:value});
this.customOptionVal是ko.observableArray()
以上代码的输出为:
0: {name: "stack"}
我想要这样的输出:
mykey: {name: "stack"}
该怎么做?
推荐答案
如果可以使用简单的observable而不是observableArray(因为数组将始终使用索引而不是自定义键),则可以将customOptionVal
设置为可观察对象:customOptionVal = ko.observable({})
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({})
现在,您可以使用customOptionVal()
访问可观察对象内部的对象,然后可以将密钥添加到该对象中,例如:customOptionVal()[yourKeyHere] = {name: "stack"}
.
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>
这篇关于淘汰赛:使用动态键在ko可观察数组中推送值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!