1
votes

I need some help with js/knockout/databindings.

In my code I am receiving an object like this: Received object

I wish to show the value in a dropdown, and the key should be stored as the value. I tried using some knockout data-bind like this:

<select id="routeTable" class="form-control" data-bind="
                            options: availableRouteTables,
                            optionsText: availableRouteTables.key,
                            optionsValue: availableRouteTables.value,
                            value: selectedRouteTable,
                            optionsCaption: '- velg rutetabell -'"></select>

I know that "availableRouteTables.key" and "availableRouteTables.value" are wrong, but it was just to explain/show what I want.

As of now the object only looks like this in JS:

this.availableRouteTables = availableRouteTables;

In the dropdown it is shown like this: Dropdown failure

Can someone help me with identifying the issue and fix it? thanks a lot!

1

1 Answers

0
votes

When you receive the data you have to change it's structure to work with the options binding:

// Convert to array of objects with value and text properties
var availableRouteOptions = [];
for(var key in availableRouteTables) {
    availableRouteOptions.push({
    value: key,
    text: availableRouteTables[key]
  });
}

And you have to change your bindings:

options: availableRouteOptions,
optionsText: 'text',
optionsValue: 'value',