Search code examples
javascriptarraysodatasapui5metadata

How to push additional fields to a javascript array from an oData result


I have a ramdom array in javascript

var dataModel = [];

I've queried an oData url and I want to fill the result in my dataModel [] array. And, for each item I want to add additional fields

odataMod.read(
        "/",
        null, [],
        true,
        function (oData, oResponse) {
            var data = oData.results;

            data.forEach(function (item) {
                //Add the object 
                dataModel.push(item);
                //I want to add additional fields to every object in data 
                dataModel.push(item.ObjectType = "Chevron");
                dataModel.push(item.HierarchyNodeLevel = 0);
                dataModel.push(item.IsCriticalPath = false);
                dataModel.push(item.IsProjectMilestone = false);
                dataModel.push(item.DrillDownState = "expanded");
                dataModel.push(item.Magnitude = 5);

...

Note : the ObjectType , DrillDownState , Magnitude (etc...) are the fields that I want to add with their values Chevron, 0, false (etc...)

Below is a screenshot of the current result :

enter image description here

But I want to add the additional properties inside each item and not outside , what I am doing wrong? In other word, I want the additional fields to be inside the metadata

Below is a sc of where I would like to add the items :

enter image description here


Solution

  • Maybe I'm misunderstanding, but I think you want only one push per item in the response. The other pushes ought to be replaced with setting properties on a copy of the item...

            data.forEach(function (item) {
                item.ObjectType = "Chevron";
                item.HierarchyNodeLevel = 0;
                item.IsCriticalPath = false;
                item.IsProjectMilestone = false;
                item.DrillDownState = "expanded";
                item.Magnitude = 5;
                dataModel.push(item);  // note: just one push
    
                // alternatively, so as to not mutate item...
                // const dataModelItem = Object.assign({
                //    ObjectType: "Chevron",
                //    HierarchyNodeLevel: 0,
                //    etc.
                // }, item);
                // dataModel.push(dataModelItem);
            }