0

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?

Keval Mehta
  • 689
  • 3
  • 28
  • `customOptionVal` must be an array? Can it be just an observable object? like: `ko.observable({});` ? – Calvin Nunes Jan 22 '19 at 12:06
  • In case of arrays, you will always get indices....Keys makes more sense in case of objects (like dictionaries in C#) – gkb Jan 22 '19 at 12:08
  • 1
    There are no "keys" in Javascript arrays, only positive integer indexes. You need to explain the intended use case better, so we can suggest a optimal strategy for JS/Knockout. – Tomalak Jan 22 '19 at 12:49

1 Answers1

2

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>
Calvin Nunes
  • 6,376
  • 4
  • 20
  • 48
  • Hi Calvin. Yes. customOptionVal must be ko observable array. – Keval Mehta Jan 22 '19 at 13:02
  • Btw, can you please tell me can I remove array index by specific field value from ko observablearray? – Keval Mehta Jan 22 '19 at 13:03
  • This is completely another question. But for this, it would be much easier as an object than an array (once again). Suggestion, try to create a custom function to remove the observable, then edit the contents and create another function to convert it back to observable – Calvin Nunes Jan 22 '19 at 13:21
  • Hi @Calvin. Can you please look over that ? https://stackoverflow.com/questions/54320140/knockout-remove-array-element-by-specific-field-value – Keval Mehta Jan 23 '19 at 04:44