How to group and read an array using knockout.js data binding: with


jhutchings

I am trying to group an array

[{ "Name": "test1", "Other": "Junk" }, 
{ "Name": "test1", "Other": "Junk2" }, 
{ "Name": "test2", "Other": "Pile" }]

I am using the following method to group by attributes.

var groupBy = function (xs, key) {
return xs.reduce(function (rv, x) {
        (rv[x[key]] = rv[x[key]] || []).push(x);
        return rv;
    }, {});
};

My output is, "test1": {children info}, "test2": {one child info}

I am using Knockout.js to pass this information to a modal, I am using data-bind="with: results"

I'm just not sure how to display the result as

test1 - (2) count/length of *test1 test2 - (1) count/length of *test2

I've tried using data-bind="foreach: $parent" and that doesn't seem to work. I also tried setting the object as a parent called UnpackedItems and then using foreach on the UnpackedItems.. that didn't work either.

<div class="modal fade" id="myModal" data-bind="with: TheseUnpackedItems" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Unpacked Items</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            </div>
            <div class="modal-body">
                <table style="margin: auto;" class="table">
                    <tbody data-bind="foreach: UnpackedItems">
                        <tr>
                            <td>
                                <p class="form-control-static" data-bind="text: Name"></p>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

self.ShowUnpacked = function(vm) {

  var groupBy = function(xs, key) {
    return xs.reduce(function(rv, x) {
      (rv[x[key]] = rv[x[key]] || []).push(x);
      return rv;
    }, {});
  };

  const Property = "Name";
  const GroupedUnpackedItems = groupBy(vm.UnpackedItems, Property);

  var test = JSON.stringify(GroupedUnpackedItems);

  var m = { "UnpackedItems": GroupedUnpackedItems }

  self.TheseUnpackedItems(vm);
}

I don't get any errors, however, no data is actually displayed.

you

UnpackedItemsis an object. So, you can't use foreachbindings. You can loop over the keys of the object usingObject.keys()

<tbody data-bind="foreach: Object.keys(UnpackedItems)">
    <tr>
        <td>
            <p class="form-control-static" data-bind="text: $data"></p>
        </td>
    </tr>
</tbody>

Here is a working snippet:

const groupBy = function(xs, key) {
  return xs.reduce(function(rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};
  
function viewModel() {
  const self = this;
  const UnpackedItems=[{Name:"test1",Other:"Junk"},{Name:"test1",Other:"Junk2"},{Name:"test2",Other:"Pile"}],
    Property = "Name",
    GroupedUnpackedItems = groupBy(UnpackedItems, Property),
    m = { "UnpackedItems": GroupedUnpackedItems }

  self.TheseUnpackedItems = ko.observable(m);
}

ko.applyBindings(new viewModel)
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div id="myModal" data-bind="with: TheseUnpackedItems">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Unpacked Items</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      </div>
      <div class="modal-body">
        <table style="margin: auto;" class="table">
          <tbody data-bind="foreach: Object.keys(UnpackedItems)">
            <tr>
              <td>
                <p class="form-control-static" data-bind="text: $data"></p>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

Related


Data binding array elements as values using knockout

Guto Is there a way to bind array elements as input or select values? something like this var ViewModel = function() { var self = this; self.array = ko.observableArray([undefined, undefined, undefined]); self.text = ko.computed(function() { return

Data binding array elements as values using knockout

Guto Is there a way to bind array elements as input or select values? something like this var ViewModel = function() { var self = this; self.array = ko.observableArray([undefined, undefined, undefined]); self.text = ko.computed(function() { return

Data binding array elements as values using knockout

Guto Is there a way to bind array elements as input or select values? something like this var ViewModel = function() { var self = this; self.array = ko.observableArray([undefined, undefined, undefined]); self.text = ko.computed(function() { return

Knockout.js data binding using jQuery

username I have a button that I want to bind to a method in the VM using knockout. I am using the following code <button type="button" class="btn btn-primary" id="cmdCreateConnection" data-bind="click: function(data, event) {

Knockout.js data binding using jQuery

username I have a button that I want to bind to a method in the VM using knockout. I am using the following code <button type="button" class="btn btn-primary" id="cmdCreateConnection" data-bind="click: function(data, event) {

Knockout.js data binding array to checkbox list

Michael Marohnic Patient 1 Patient.Age = '25' Patient.Injury[0].Date = '2015-01-01' Patient.Injury[0].Type = 'Burned' Patient.Injury[1].Date = '2015-01-27' Patient.Injury[1].Type = 'Sprained Ankle' Patient 2 Patient.Age = '17' Pati

Knockout.js data binding array to checkbox list

Michael Marohnic Patient 1 Patient.Age = '25' Patient.Injury[0].Date = '2015-01-01' Patient.Injury[0].Type = 'Burned' Patient.Injury[1].Date = '2015-01-27' Patient.Injury[1].Type = 'Sprained Ankle' Patient 2 Patient.Age = '17' Pati

Ajax data binding with Knockout Js

Kitty Sarvaj I am using knockout js and I am finding it difficult to bind data in ajax get method, I have created model, viewModel and ajax function, I have ajax method in the same js file where I am creating viewModel on page load ajax and try to bind my html

Ajax data binding with Knockout Js

Kitty Sarvaj I am using knockout js and I am finding it difficult to bind data in ajax get method, I have created model, viewModel and ajax function, I have ajax method in the same js file where I am creating viewModel on page load ajax and try to bind my html

How to handle data binding, knockout

Kagdas Aslan I have a client who is a member of a website. He has to fill out a form very frequently every time. That's why he asked me to develop an app for him that automates the process. When I do it with the webBrowser control, I can log in, but after that

How to bind multiple events in data binding using knockout

Noiti New to knockout JS. I'm still learning stuff. I am trying to bind multiple events in a single data binding. How can I do this? I need to execute 2 functions on a single event. HTML <span class="btn btn-default btn-file btn-primary">Browse<input type="fil

How to apply binding and persist input value using Knockout JS?

Kees C. Bakker I am building an HTML/KnockoutJS application. My web server returns a form with input fields and information. When I update the model and execute ko.applyBindings, the input value is naturally overwritten by the model. Is there a way to automati

How to apply binding and persist input value using Knockout JS?

Kees C. Bakker I am building an HTML/KnockoutJS application. My web server returns a form with input fields and information. When I update the model and execute ko.applyBindings, the input value is naturally overwritten by the model. Is there a way to automati

How to apply binding and persist input value using Knockout JS?

Kees C. Bakker I am building an HTML/KnockoutJS application. My web server returns a form with input fields and information. When I update the model and execute ko.applyBindings, the input value is naturally overwritten by the model. Is there a way to automati

How to apply binding and persist input value using Knockout JS?

Kees C. Bakker I am building an HTML/KnockoutJS application. My web server returns a form with input fields and information. When I update the model and execute ko.applyBindings, the input value is naturally overwritten by the model. Is there a way to automati

How to apply binding and persist input value using Knockout JS?

Kees C. Bakker I am building an HTML/KnockoutJS application. My web server returns a form with input fields and information. When I update the model and execute ko.applyBindings, the input value is naturally overwritten by the model. Is there a way to automati

Knockout js: data binding click not working

Benjamin Baggins I can't trigger the knockout feature logMyStuffon my website with a simple button click . Note that I've added <button>, <a>and <div>tried to get it to work. I made a JS fiddle, but the JS fiddle worked. Here is my code: var SearchFilterViewMo

Knockout.js data binding to ViewModel

Damon I'm trying to figure out KnockOut data binding and am struggling to get a simple form to bind to a ViewModel. I am using WebAPI to extract my JSON data. This is my ViewModel, when this "find" method is called, it creates a new WorkOrder object and popula

Knockout.js data binding to ViewModel

Damon I'm trying to figure out KnockOut data binding and am struggling to get a simple form to bind to a ViewModel. I am using WebAPI to extract my JSON data. This is my ViewModel, when this "find" method is called, it creates a new WorkOrder object and popula

Does data binding show div knockout js

XAF So I'm trying to display some divs that basically show boxes of different colors based on their number, basically both AA and B return 5, so they should show, while other divs should be empty or empty, or even not show the divs at all, But for some reason