Unable to retrieve an array in SAPUI5 and assign it to a JSONModel

I encountered an issue with accessing an array where I stored data from a model read operation. The array, named aData, contains row data for a table and everything seems to be working correctly as all the data is present.

This code snippet is executed after opening a value help dialog, and I intend to populate the table with the retrieved data.

        var oTestModel = this.getModel();
        oTestModel.read("/shrhelpSet", {
            filters: [oFilterObject, oFilterField, oFilterLang],
            success: function(oRetrieveResults){
                //console.log(oRetrieveResults);

                var oDatas2 = oRetrieveResults;
                var test1 = oDatas2.results;

                var aData = [];
                var index = oDatas2.results.length;
                var i;
                for (i=0; i<index; i++) {       

                    aData.push("{Key: '" + oDatas2.results[i].key + "', Value: '" + oDatas2.results[i].value + "'}");
                }

                // aData Array  
                console.log("aData: " + aData);

            },

            error: function(oError){
                console.log(oError);
            }
        });

The following block of code comes after the model read operation. Here, I have an array containing column data for my table. The oModel2 consists of the column data defined in aColumnData and the rows fetched above are stored in aData. However, there seems to be an issue as it either doesn't return any data or only displays an object. Any tips on handling this better or a solution to this problem?

        var aColumnData = [{
            columnId: "Key"
        }, {
            columnId: "Value"
        }];

        var oModel2 = new sap.ui.model.json.JSONModel();

        oModel2.setData({
            columns: aColumnData,
            rows: aData // THIS IS THE RESULT OF MY MODEL, the results are in aData but i cant access it here
        });

        oTable.setModel(oModel2);

        oTable.bindColumns("/columns", function(index, context) {
            var sColumnId = context.getObject().columnId;
            return new sap.ui.table.Column({
                id : sColumnId,
                label: sColumnId,
                template: sColumnId
            });
        });
        oTable.bindRows("/rows");

Answer №1

It seems that the issue may lie in the fact that you are pushing strings instead of objects into your array:

aData.push("{Key: '" + oDatas2.results[i].key + "', Value: '" + oDatas2.results[i].value + "'}");

The correct format for your object should be something similar to this:

{
   Key: oDatas2.results[i].key,
   Value: oDatas2.results[i].value
}

Answer №2

To improve your code, consider moving the section that requires access to the received data into the success handler. It is also advisable to create objects instead of using strings as noted in another answer.

this.getModel().read("/shrhelpSet", {
filters: [oFilterObject, oFilterField, oFilterLang],
success: function (oRetrieveResults) {
    var aData = oRetrieveResults.results.map(function (oResult) {
        return {
            Key: oResult.key,
            Value: oResult.value
        };
    });

    var aColumnData = [{
        columnId: "Key"
    }, {
        columnId: "Value"
    }];

    var oModel = new sap.ui.model.json.JSONModel({
        columns: aColumnData,
        rows: aData
    });

    oTable.setModel(oModel);

    oTable.bindColumns("/columns", function (index, context) {
        var sColumnId = context.getObject().columnId;
        return new sap.ui.table.Column({
            id: sColumnId,
            label: sColumnId,
            template: sColumnId
        });
    });

    oTable.bindRows("/rows");
}.bind(this),

error: function (oError) {
    console.log(oError);
}
});

Answer №3

There seems to be no issue with your view.

var oTable = new sap.ui.table.Table({
  rows: '{/rows}',
  title: new sap.m.Title({
    text: "Test"
  })
});

oTable.bindColumns("/columns", function(index, context) {
  var sColumnId = context.getObject().columnId;
  return new sap.ui.table.Column({
    label: sColumnId,
    template: sColumnId
  });
});

var model = new sap.ui.model.json.JSONModel({
  columns: [{
    columnId: "Key"
  }, {
    columnId: "Value"
  }],
  rows: [
    { Key: "K1", Value: "V1" },
    { Key: "K2", Value: "V2" }
  ] 
});

oTable.setModel(model);
oTable.placeAt('content');
<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta http-equiv='Content-Type' content='text/html;charset=UTF-8'/>
    <script src="https://sapui5.hana.ondemand.com/resources/sap-ui-core.js" 
            id="sap-ui-bootstrap"
            data-sap-ui-libs="sap.ui.commons,sap.ui.table,sap.m" 
            data-sap-ui-xx-bindingSyntax="complex"
            data-sap-ui-theme="sap_belize"></script>
  </head>
  <body id="content" class="sapUiBody sapUiSizeCompact">
  </body>
</html>

It seems that there might be an error in your model. Perhaps you are attempting to modify the model results like this.

success: function(oRetrieveResults){
    var aData = oRetrieveResults.results.map(function(data) {
        return {
            Key: '"' + data.key + '"',
            Value: '"' + data.value + '"'
        };
    });
    this.setProperty("/results", oData);
},

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Stripping out only the position attribute using jQuery

I have implemented a code with the following characteristics: The navigation items' texts are hidden behind certain Divs, which I refer to as Navigation Divs. When the mouse hovers over these pixels (navigation Divs), the text that is behind the ...

Create a webpage in full screen mode with a video player that fills the entire screen

Here is the HTML code I am working with: <div id="container"> <video id="video" src="video.ogv" loop></video> </div> The "container" div and video element occupy the entire screen. #container { po ...

Omit certain components from the JQuery ListNav plugin

I recently incorporated the Jquery plugin for record filtration. I obtained this plugin from the following link: After successfully implementing the plugin, I encountered an issue where it was counting the headings along with the alphabet filters in my co ...

Monitor the x and y positions for platformer game interactions using only JavaScript and jQuery

I am currently working on a 2D platformer game as part of my college project alongside my friends. We are using jQuery and pure JS for development. So far, we have been able to move the character left and right using jQuery's animate function, and ena ...

An error in typescript involving a "const" assertion and a string array

Currently, I am diving into the world of Typescript along with React. However, an error has emerged in my path that I can't seem to figure out. It's puzzling why this issue is occurring in the first place. Allow me to elaborate below. const color ...

Tips for submitting an AJAX form in grails without relying on a traditional submit button

I am utilizing a g:formRemote tag to submit a form via ajax. <g:formRemote name="listAll" update="menuItemAJAX" url="[controller: 'superWaiter', action:'menuItem']" onSuccess="additionalContent()"> <a h ...

@HostBinding in Angular 2 does not trigger change detection

When using @HostBinding in conjunction with Chrome's Drag and Drop API, the code looks like this: @Directive({ selector: '[sortable-article]' }) export class SortableArticleComponent { @HostBinding('class.dragged-element') ...

Determining when a text area has selected text without constant checking

class MarkdownEditor extends React.Component { constructor(props) { super(props); this.timer = null; this.startIndex = null; this.endIndex = null; } componentDidMount() { this.timer = setInterval(() => { this.setSelectio ...

Tips for submitting a form textarea input from CKEditor using AJAX

I am currently utilizing CKEditor, jQuery, and the jQuery form plugin. My objective is to submit the content of the CKEditor form through an Ajax query. Below is the code I have implemented: <form id="article-form" name="article-form" method="post" act ...

"Learn the steps to access a JSON file directly from a URL within a Next.js

My goal is to upload a JSON file to the server from a URL, open it, parse it, and display its features on Google Maps. However, I am encountering an error with the "fs" library preventing me from opening the file. Below is the code: "use client" ...

React: When an array state is controlling my components, why aren't they re-rendering?

I am facing an issue with my app where the className of buttons is not updating correctly when clicked. It seems that only active buttons trigger a re-render, while non-active ones do not. This behavior is confusing to me. Here's the code snippet for ...

In React JS, the data from my response is not being saved into the variable

My goal is to store the response data in the variable activityType. Within the useEffect function, I am iterating over an API based on the tabs value. The API will return a boolean value of either true or false. While I can successfully log these values ...

"Navigate through the page by scrolling with your mouse all the way to 100

Is it possible to trigger an action when a user starts scrolling using the mousewheel? I've searched online but all I found was information on 100% scroll on click. I want the window to automatically be scrolled down to 100% as soon as the user starts ...

What are the various undisclosed schema types in A-Frame?

I've been exploring different examples of property types in the official documentation and various Github repositories (though now I can't remember which ones). The latter introduced me to unique properties like "min" and "max" for numbers, as we ...

Having trouble with @here/maps-api-for-javascript in Next.js - it's not functioning

Can anyone help me understand why @here/maps-api-for-javascript is not functioning properly in my Next.js application and producing the following error message: import H from "@here/maps-api-for-javascript"; export default H; ^^^^^^ SyntaxErr ...

Issues with rendering TextGeometry in Three.js

Despite my attempts to replicate the demo code, I am unable to successfully render TextGeometry. The necessary font file is correctly uploaded on the server. var loader = new THREE.FontLoader(); loader.load( 'fonts/open-sans-regular.js' ...

Mastering the correct usage of the submitHandler method in the jQuery validation plugin

Here is a snippet of documentation from the jQuery validation plugin: "Use submitHandler to execute some code before submitting the form, without triggering the validation again." submitHandler: function(form) { $.ajax({ type: 'POST&apos ...

Setting a background image in ReactJS

I've been struggling with this issue for a while now, and after doing a lot of research online, I came across a solution that is supposed to work in index.css body { background-image: url(../src/components/images/photo.jpeg) no-repeat center cent ...

What are the steps to create a responsive Coin Slider?

Once the slider is generated, it appears that there is no built-in method to resize it, causing issues with responsive design. Is there a way to adjust the size of the Coin Slider plugin based on the media queries in Twitter Bootstrap 3? Take a look at C ...

Breaking auto-update functionality when using the 'dd-slick' jQuery plugin to style chained drop-downs

Utilizing the jquery.ddslick.min.js plugin from jQuery for creating customized drop-down menus with image options. Additionally, incorporating the jquery.chained.min.js script to automatically update the content in the second select box based on the select ...