Search code examples
javascriptjqueryknockout.jsknockout-mapping-plugin

How can I copy an observable in an observableArray to another observableArray?


I'm new to JS and Knockout. I want to copy a particular observable inside an observableArray to another observableArray. How can I do this?

HTML

<table>
    <thead>
        <tr>
            <th>Passenger Name</th>
            <th>Meal</th>
            <th>Amount ($)</th>
            <th></th>
        </tr>
    </thead>
    @*render a copy of seats child elements for each entry in the seats array*@
    <tbody data-bind="foreach: seats">
        <tr>
            <td data-bind="text: name"></td>
            @*update the view to make use of the formatted Price*@
            <td>
               <select data-bind="options: $root.availableMeals, 
                                  value: meal, optionsText: 'mealName'">
               </select>
            </td>
            <td data-bind="text: formattedPrice"></td>
            <td><a href="#" data-bind="click: $root.removeSeat">Remove</a></td>
        </tr>
    </tbody>
</table>

Requirements

requirements


Solution

  • I've created a JS fiddle that shows how you can move items between observable arrays, using the below code:

    HTML

    <p>first list:</p>
    <table>
        <tbody data-bind="foreach: contents">
            <td> <strong>
                     <span id="textKey" data-bind="text: displayKey" />    
                </strong>
            </td>
            <td>
                <input id="textValue" type="text" data-bind="value: displayValue" />
            </td>
            <td>
                <input type="button" data-bind="click: $root.copyItem" value="select" />
            </td>
        </tbody>
    </table>
    
    <p>Second list:</p>
    
    <table>
        <tbody data-bind="foreach: selectedContents">
            <td> <strong>
                     <span id="textKey" data-bind="text: displayKey" />    
                </strong>
            </td>
            <td>
                <input id="textValue" type="text" data-bind="value: displayValue" />
            </td>       
        </tbody>
    </table>
    

    View Model:

    function ViewModel() {
        var self = this;
    
        self.contents = ko.observableArray([{
            "displayKey": "Fruit",
                "displayValue": "Bananas"
        }, {
            "displayKey": "Colour",
                "displayValue": "Red"
        }, {
            "displayKey": "Car",
                "displayValue": "Ferrari"
        }]);
        self.selectedContents = ko.observableArray([]);
    
        self.copyItem = function(item) {
            self.selectedContents.removeAll();
            self.selectedContents.push(item);
        }
    }
    ko.applyBindings(new ViewModel());