0

I am using Knockout.js as a way to dynamically update a view from a JSON response. The JSON looks like the following:

var data = {
  "Properties": {
    "Engine Capacity": "1499cc",
    "Doors": 3,
    "Extras": [
      "LED lights",
      "4WD"
    ],
    "Model": "123a"
  }
};

I have figured out a way in JavaScript to construct my <li> elements:

for (var field in data['Properties']) {
  var value = data['Properties'][field];
  var out = '<li>' + field + ': ' + value + '</li>';
  console.log(out);
  // <li>Engine Capacity: 1499cc</li>
  // <li>Doors: 3</li>
}

I know this isn't an ideal way as constructing HTML in JavaScript isn't best practice. There is a way to print out the value in Knockout but with hardcoded values:

<ul data-bind="foreach:$root.Properties">
  <li data-bind="text:$data:Doors"></li>
  <li data-bind="text:$data.Model"></li>

But I was wondering whether it could be possible to get Knockout.js to look like what I'm returning in the JavaScript code?

Rick
  • 4,030
  • 9
  • 24
  • 35
  • You need to do some kind of mapping. Maybe [`ko.mapping.fromJSON`](http://knockoutjs.com/documentation/plugins-mapping.html)? – Adelin Jul 18 '18 at 08:26

1 Answers1

0

Here's how you can do it:

var data = {
  "Properties": {
    "Engine Capacity": "1499cc",
    "Doors": 3,
    "Extras": [
      "LED lights",
      "4WD"
    ],
    "Model": "123a"
  }
};


var viewModel = {
    data: ko.mapping.fromJS({"Properties": data.Properties})
};

ko.applyBindings(viewModel);​

<ul data-bind="foreach: data.Properties">
    <li>
        <b data-bind="foreachprop: props"> : 
            <span data-bind="value"> </span>
        </b>
    </li>
</ul>

More reference:

Harshal Yeole
  • 4,812
  • 1
  • 21
  • 43