问题
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