JSFiddle - React, Tailwind, and code Playground

by origineil

HTML

<table id='usingMapping'>
    <tbody data-bind="foreach: gastos">
        <tr>
            <td data-bind="text: $data.id"></td>
            <td data-bind="text: $data.name"></td>
            <td data-bind="text: $data.value"></td>
            <td data-bind="text: $root.accountLookup($data.accountId).Name"></td>
            <td data-bind="text: $root.accountLookupByUtil($data.accountId).Name"></td>
        </tr>
    </tbody>
</table>

JavaScript

var data = [
{"$id":"1","Id":1,"Name":"apple","Value":100.0,"AccountId":1,"Account":
    {"$id":"2","Id":1,"Name":"Cash"}},
{"$id":"3","Id":2,"Name":"pear","Value":50.0,"AccountId":1,"Account":
    {"$ref":"2"}},
{"$id":"4","Id":3,"Name":"raspberry","Value":10.0,"AccountId":1,"Account":
    {"$ref":"2"}},
    {"$id":"5","Id":4,"Name":"jelly","Value":10.0,"AccountId":1,"Account":
    {"$id":"3","Id":2,"Name":"Credit"}},
    {"$id":"5","Id":5,"Name":"grape","Value":11.0,"AccountId":1,"Account":
    {"$ref":"3"}},
]

var vm = {
    gastos: [],
    
    accounts: {},
    accountLookup: function(accountId){
      return this.accounts[accountId];
    },
    accountLookupByUtil: function(accountId){
        
        var gasto =  ko.utils.arrayFirst(this.gastos, function(item) {
            if(item.account['$id'] == accountId)
            { 
              return item
            }             
        });
       
        return gasto.account;
    }
}


var populate = function () {
  data.forEach(function(o) {          
   var accountId = o.Account["$id"]
   if(accountId)
   {
    vm.accounts[accountId] = o.Account;
   }
   vm.gastos.push(new gastoVM(o.Id, o.Name, o.Value, o.Account));
  });
 };

var gastoVM = function(Id, Name, Value, Account) {
        var self = this; 
        self.id = Id;
        self.name = Name;
        self.value = Value;
        self.accountId = Account['$id'] |  Account['$ref'];
        self.account = Account;
    };

populate();
ko.applyBindings(vm)