how to push data to existing sapui5 model - javascript

I have a Json Model in sapui5 as - //console.log(dModel);
My new data response is as follows - //console.log(response);
Now I want to push new data(only the data part) to the existing model, inside /modelData/data.
code I am trying -
sap.ui.getCore().getModel().getProperty("/modelData/data").push(response.data);
This code is pushing the data but as -
After 19(old values) it is pushing all the objects inside 20th as 0, 1, 2... The Ideal way should be after 19 I should get 20, 21, 22 and so on.
What changes I need to make to get this, Thank you ... please suggest.

If you need to add new items to your model, you should use it like this:
var oModel = sap.ui.getCore().getModel();
var aData = oModel.getProperty("/modelData/data");
aData.push.apply(aData, response.data);
oModel.setProperty("/modelData/data", aData);
The difference is you first retrieve the array with data, add to the array, and then set the property with the updated array
Edit: Ok, makes sense now: you are adding an array to an array. And using 'push' just adds a new entry with whatever object you are adding. So you are adding a single entry (which happens to be an array)
See updated answer

Try this:
for(var i = 0; i < response.data.length; i++){
sap.ui.getCore().getModel().getProperty("/modelData/data").push(response.data[i])
}

Related

How does manipulating multiple checkbox selection code work?

I am following ag-grid's official tutorial:
https://www.ag-grid.com/angular-getting-started/?utm_source=ag-grid-readme&utm_medium=repository&utm_campaign=github
I reached the part where I have to manipulate the information regarding the selected checkboxes. However, the documentation is not detailed; It does not explain how the code actually works. Perhaps, this makes sense since it is not their job to explain in detail. However, for someone like me who doesn't have solid experience with working with angular technology and who wants to truly understand how things work, this is troublesome!
In the html file, I have been asked to add this:
<button (click)="getSelectedRows()">Get Selected Rows</button>
And in app.component.ts, I have been asked to add this:
getSelectedRows() {
const selectedNodes = this.agGrid.api.getSelectedNodes();
const selectedData = selectedNodes.map(node => node.data);
const selectedDataStringPresentation = selectedData.map( node => node.make + ' ' + node.model).join(', ');
alert('Selected nodes: ${selectedDataStringPresentation}');
}
If someone could explain what the typescript code is doing exactly, that would be very generous.
Thank you!
I guess agGrid is the service storing your mock values, this simply gets an array of data from somwhere.
selectedData is another array that is created by transforming (transforms the array while providing a new reference, thus not modifying the original array) the selectedNodes array and only selecting the data property of each node.
selectedDataStringPresentation is the same, but this time it provides an array of formatted strings by merging the properties make and model of each object from selectedData.
What you probably fail to grasp is the usage of the ES6 (JavaScript standard) functions that are used here, and especially the map() function.
Here is the official documentation of the map() function for arrays : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
Simply explained, it is a function that iterates over an array, and transforming each object by applying the function declared in the map, returning the results in a new array.
If you take the example of selectedData, you can translate the operation into this :
Loop over each object of selectedNodes, and return only the property data of the current object. Push the results in a new array.
This is especially useful when you want to work on different arrays that serve different purposes. For example, imagine you have a service that contains a list of objects. A backend service will provide you an array of numbers representing the IDs of the objects you have in your service.
You can then use the map() function to transform the array of IDs into an array of your Objects stored in your service easily.
Darn #Alex Beugnet(upvote) beat me to the punch! I'm going to post anyway as I was in the middle of writing it all.
Firstly I'm not sure how much of TypeScript you already know, I apologize if much of these becomes trivial, the purpose is only to ensure maximum clarification to the question in understanding the logic.
In the Enable Selection portion of the guide, you are essentially enabling multiple row selection in the grid and having the button return the data from those selected rows.
In order to see what's happening with the getMultipleRows() function, it would be best to visualize it via the Debugger provided in browsers, I'm using Chrome Developer Tools (hit F12), I would highly recommend it for understanding what is happening in the logic.
const selectedNodes
Let's start by selecting say 2 rows, I have selected the Porsche Boxster 72000 and Ford Mondeo 32000. After selecting them I click on the 'Get Selected Rows' button which triggers the getSelectedRows() function:
const selectedNodes = this.agGrid.api.getSelectedNodes();
The above line is assigning the constant variable 'selectedNodes' the RowNodes from AgGrid. Here you are using the AgGridNg2 method getSelectedNodes() to return the selected node data, which you would be returned an array in the form of:
[RowNode, RowNode] //(each for the row we have selected)
Looking into a RowNode we get:
These are all the RowNode properties provided by the AgGrid framework, you can ignore all of these object properties as you are only concerned with the 'data' property as you'll see in the next line of code!
const SelectedData
const selectedData = selectedNodes.map(node => node.data);
Here we are setting 'selectedData' as an array of RowNode.data, basically trying to get the data property from the RowNodes into an array.
The above line can basically be assumed as:
let selectedData = [];
for (let i = 0; i <= selectedNodes.length - 1; i++){
selectedData[i] = selectedNodes[i].data;
}
In which we are just trying to get the data property into a new constant variable 'selectedData'. Look at the documentation in order to better understand this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
const selectedData would be returned as:
[
{
make: "Porsche",
model: "Boxster",
price: 72000,
},
{
make: "Ford",
model: "Mondeo",
price: 32000
}
]
const selectedDataStringPresentation
const selectedDataStringPresentation = selectedData.map( node => node.make + ' ' + node.model).join(', ');
We take the selectedData array and concatenate the Make and Model as a single element for the array and adding a comma in the end. We would get "Porsche Boxter, Ford Mondeo".
let selectedData = [
{
make: "Porsche",
model: "Boxster",
price: 72000,
},
{
make: "Ford",
model: "Mondeo",
price: 32000
}
]
let selectedDataStringPresentation = [];
for (let i = 0; i <= selectedData.length - 1; i++){
selectedDataStringPresentation[i] = selectedData[i].make + ' ' + selectedData[i].model;
}
selectedDataStringPresentation = selectedDataStringPresentation.join(', ');
console.log(selectedDataStringPresentation);
alert()
And the last line,
alert('Selected nodes: ${selectedDataStringPresentation}');
You are going to send an alert in the browser that will display the selectedDataStringPresentation array.

How to make an array from JSON?

Couldn't think of better title.
Important to note: I'm new to js and I guess its the reason I can't figure it out by myself.
I have a JSON array returned from a database, the JSON array represent a set of points.
Example of the JSON array:
var JSON_array = [{lat:1,lng:2}, {lat:1,lng:3},{lat:2,lng:3}...]
I want to make a different array whose elements will be a function and the variables of the function will be the elements from the JSON array, like so:
var coordinates = [
new google.maps.LatLng(1, 2),
new google.maps.LatLng(1, 3),
new google.maps.LatLng(2, 3),
....
];
I made a function using forEach that counts the elements of the JSON array (for learning and trying to find a way to what I want) but I cant think of a way make the array mentioned above.
You could use Array map method:
var coordinates = JSON_array.map(function(coordinate) {
return new google.maps.LatLng(coordinate.lat, coordinate.lng);
})
This method gives you an new array based on (1) the original array and (2) how you deal with each element. Here's more detailed doc for the method.
you can also use regular for loop
coordinates = [];
for(var i=0;i<JSON_array.length;i++){
coordinates.push(new google.maps.LatLng(JSON_array[i].lat,JSON_array[i].lng));
}
For mapping element from one array to another you can use Array.prototype.map function like
var JSON_array = [{lat:1,lng:2}, {lat:1,lng:3},{lat:2,lng:3}...];
var coordinates = JSON_array.map(function(el){ return new google.maps.LatLng(el.lat, el.lng)});
As Grundy commented you can just do:
coordinates = JSON_array.map(function(x) {
return new google.maps.LatLng(x.lat, x.lng);
});
You might want to get your nomenclature straight though, this has nothing to do with JSON.

Storing values in array and retrieving from array when checkbox is checked

I am storing some values in array like this.
var test = [];
I am pushing the values to this array as test.push(sample);
I have some logic for calculating this value
var sample= (a/b.length)*100;
When I click on a button, the above logic for calculating value of sample is done and once I got the value of sample I am pushing it to test[] array. Now I want to retrieve all the values from the test[] array whenever I check the checkbox. I am able to do all this but I am facing a problem here. only the last pushed value is saving. but I want to save all the values that are being pushed. can anyone please help me in solving this issue.
Quick response is needed and appreciated
Regards
Hema
You need to use 2 dimensional array for this.
Use
var test= new Array();
then assign value test['someKey']=sample;
or test.push(sample); . you can retrieve array value like alert(test[0]) or by iterating array with $.each(test,function(index,value){alert(value)});
What you want to do is create an Array which would function as a list of value sets.
You would then be able to push all the changes into an array, and put it in the list.
for instance:
var mainList = new Array();
var changeListA = new Array();
var changeListB = new Array();
// do some stuff on change list **a** .. push(something)
changeListA .push(something);
changeListA .push(something);
changeListA .push(something);
// do some stuff on change list **b** .. push(something)
changeListB .push(changeListB);
mainList.push(changeListA);
Your question is not perfectly clear to me, however I can at least provide a small jsFiddle that proves to you that (how) array.push works.
Other answers indicate that what you want is either a two dimensional array, or a "hashmap" or "associative array" where the array values are stored using a key name. The code here can be used in the fiddle to achieve either or...
http://jsfiddle.net/xN3uL/1/
// First if you need 2 dimensional arrays:
myArray.push( ["Orange", "Apple"] );
myArray.push( ["Mango", "Pineapple"] );
// Secondly, if you need hashmap or associative array:
var myObj = {};
myObj['key'] = 'value';
alert(myObject.key);

How Do I Make an Array of Objects a Reactive Data Source?

I have an array of objects. Say
var
sidelist = [
{
name:"asdf",
id:1234,
types:[...]
}
];
Every object is turned into a box on the page using this construct
Template.global.side = function(){
var obj = [], m;
m = 1;
for (var i in sides){
obj.push({
index : m,
object : sides[i]
});
}
return obj;
}
The HTML:
{{#each side}}
<div class="span{{this.index}}" id={{this.object.id}}>
<div class="side-head">{{this.object.name}}</div>
</template>
There is a function that creates and pushes a new object into the array. How do I make the row of boxes reactively update on the page when the array they depend on changes?
So when I add a new object a new box should appear.
If you want to use Dependencies, it can look like this:
var sidelist = ...;
var sidelist_dep = new Deps.Dependency;
Template.global.side = function(){
sidelist_dep.depend();
// Do your stuff here;
return ...;
};
// Important: call this every time you change sidelist,
// AFTER the change is made.
sidelist_dep.changed();
See: http://docs.meteor.com/#deps
In almost all cases, you should put the objects in a Meteor Collection instead of an array that is part of a reactive object. There are many reasons for this, including the following
Adding, removing, searching, and updating will all be faster
The reactivity will be on the element level instead of the array
Meteor won't re-render the whole set of objects when something is added or deleted - just the change
You can define a sort order on the collection, making it much more flexible than a fixed sequence
Take a look at Andrew Wilcox's isolate-value smart package:
https://atmosphere.meteor.com/package/isolate-value
The README contains the exact example of selectively rerendering relevant templates when values are added/removed from an array stored in a Session varaible.

push values into an array dynamically with javascript

I'm have trouble finding a way to push values into an array dynamically. I have given the following situation:
var get_anchors= new Array('pitzel','mitzel','sizzle')
current_anchor= pics[key].anchor; //has the value 'sizzle'
get_anchors[current_anchor].push(new Array('sizzle2','sizzle3'))
Javascript fails and says get_anchors[current_anchor] is undefined
How can I make get_anchors[current_anchor] work. Or is there a different way to get this done?
The desired result should look like 'pitzel','mitzel','sizzle'['sizzle2','sizzle3]
Based on your comment it looks like you want a hash map instead of an array. You can use an object for this:
var anchors = {
'pitzel': [],
'mitzel': [],
'sizzle': []
};
Then you can do:
anchors[current_anchor].push('sizzle2', 'sizzle3');
or assuming that anchors does not have a property with the value of current_anchor, simply assign a new array:
anchors[current_anchor] = ['fooX', 'fooY'];
Of course you can populate the object dynamically as well. Have a look at Working with Objects for more information.
I'm not sure I understand what you're trying to do, but I think you're trying to insert a few elements after where another occurs. This will do the trick:
var get_anchors = [ 'pitzel', 'mitzel', 'sizzle' ];
current_anchor = get_anchors.indexOf(pics[key].anchor);
get_anchors.splice(current_anchor + 1, 0, 'sizzle2', 'sizzle3');
// get_anchors = [ 'pitzel', 'mitzel', 'sizzle', 'sizzle2', 'sizzle3' ]

Categories