Search code examples
javascriptjsonmodelodatasapui5

How to get a single object in an array to a JSON model


I have a JSON model /details with 4 objects. I want the object based on the key :month.

   Object
   oData
   details:
   Array[4]
   0:Object
   1:Object
   2:Object
   3:Object
    editable:false
    key:"date"
    removeable:false
    value:"Day: TRUE, Night:False"
   4:Object
    editable:false
    key:"month"
    removeable:false
    value:"August"

The following is the code

/view

 var viewModel = that.getView().getModel();
 var viewModelData = viewModel.getData();

Solution

  • You cannot query the object directly. You have to loop and search like so:

    var viewModel = that.getView().getModel();
    var viewModelData = viewModel.getProperty("/details");
    var month = getObjectByKey(viewModelData, "month");
    
    function getObjectByKey(a, key){
      for(var i = 0; i < a.length; i++){
      if (a[i].key === key){
        return a[i];
      }
      return null;
    }