Iterate over BasicPrimitives OrgChart Items - javascript

I'm using basic primitives org chart to create a family tree. What I'd like to do is iterate over the items that have been rendered so I can save the json to the database. I've been looking over the site's reference and put this in my code:
alert(primitives.famdiagram.ItemConfig.length);
$.each(primitives.famdiagram.ItemConfig, function (key, value) {
alert(value.Id);
});
for (var i=0; i < primitives.famdiagram.ItemConfig.length; i++)
{
alert(primitives.famdiagram.ItemConfig[i].Id);
}
It gives me a length of 5, but when I try to iterate through the items with either jquery or javascript, nothing happens. How can I access the collection of items using basic primitives?

This appears to work and I'd just have to rebuild the json string:
var items = jQuery("#famdiagram").famDiagram("option", "items");
$.each(items, function (key, value) {
alert(value.id);
alert(value.title);
alert(value.parents);
});
OR just save the items array in the DB as is.

Related

Javascript array is empty when used in JSON.stringify

My project makes use of Dev Extreme and it's datagrid component. This datagrid displays data to my users where they can select individual rows on the datagrid and pass them to my backend via an API call.
In the API call, I need to pass over an array of values that I'm collecting from whichever row has been selected. When I output my array to the console, everything is how I expect it to be. Yet, when I place it in JSON.stringify() the array is empty.
Why does this happen? As I'm expecting the result to look like: { 'LoadContextIds': [1,2,3], "ReportingCobid": "20190119"}.
My logic for the above is as follows:
function runBatchWithLoadContexts() {
var data = [];
getDataGridInstance().getSelectedRowsData().done(function (rowData) {
for (var i = 0; i < rowData.length; i++) {
data.push(rowData[i].LoadContextId);
}
});
var obj = { 'LoadContextIds': data, "ReportingCobid": cobDate };
console.log(data);
console.log(JSON.stringify(obj));
}
And attached is a snippet from my console.log showing the above results as well. The top line is the output format of `data' and the bottom is the result of stringifying it.
From what I could tell (by briefly glancing at the devexterme docs), .done is asynchronous. So your for loop executes, and data array is filled, after your console logs. This explains why console.log(JSON.stringify(obj)); shows an empty array.
However, console logs actually print live objects, that can be updated as the objects themselves are updated. This explains why console.log(data); prints a non empty array.
I bet if you added console.log(JSON.stringify(data)), that too would be an empty array.
All that #junvar said is correct and if you create your obj inside the done function after the for loop, all the data is going to be there.
function runBatchWithLoadContexts() {
var data = [];
getDataGridInstance().getSelectedRowsData().done(function (rowData) {
for (var i = 0; i < rowData.length; i++) {
data.push(rowData[i].LoadContextId);
}
let obj = { 'LoadContextIds': data, "ReportingCobid": cobDate };
console.log(data);
console.log(JSON.stringify(obj));
});
}

How to iterate in Jquery over json string with multiple objects

I'm wondering how I can access each object in this json string via jquery.
The string returned looks like:
{"Appointments":["\/Date(1507238100000)\/"],"Sessions":[]}
I need access to both the Appointments object as well as the Sessions object, I can't seem to figure it out.
I tried to access the Appointments object by index like:
$.each(data, function (index, element) {
$.each(data, function (index, element) {
//alert(JSON.stringify(element, null, 4));
alert(element.Appointments[index]);
});
//value = new Date(parseInt(element.Appointments.substr(6)));
//var rowContent = "<tr><td>" + value + "</td></tr>";
//$('#appointmentsTable tbody').append(rowContent);
});
This does not work however, thoughts?
You don't have to access element by element.Appointments[index] when you are looping though an array by $.each.
For example
var data = {"Appointments":["\/Date(1507238100000)\/"],"Sessions":[]};
To loop though object in data.Appointments, you simply do this
$.each(data.Appointments, function(index, element){
console.log(element);
});
To loop though object in data.Sessions, you simply do this
$.each(data.Sessions, function(index, element){
console.log(element);
});
For more example about $.each, please refer to JQuery API Documentation here.
You don't actually need jquery for this at all.
You could use plain javascript. If your project uses ES6, you could write it as:
// extract appointments and sessions from data
let { Appointments, Sessions } = data
// iterate over appointments
Appointments.forEach((appointment, index) => { console.log(appointment) })
// iterate over sessions
Sessions.forEach((session, index) => { console.log(session) })
Basically you don't really need index inside your iteration callback - you can directly access the elements you are iterating over instead. The same would apply to your jquery function as well.
If you prefer to use jQuery, your code could be rewritten as:
$.each(data.Appointments, (index, elem) => alert(elem))

Odoo PoS get orderline product

I'm updating the update_payment_summary function in the Point_Of_Sale, this function is part of the PaymentScreenWidget.
Now I'd like to retrieve the products from the orderlines.
I tried with
var order = this.pos.get('selectedOrder');
var orderlines = order.get('orderLines').models;
But when I print orderlines I get [object Object]
Any ideas how I can get the product object of every orderline?
Yes there is a reason why it shows object.
OrderlineCollection definition.
module.OrderlineCollection = Backbone.Collection.extend({
model: module.Orderline,
});
Orderline definition in Order Model.
orderLines: new module.OrderlineCollection()
So if you observe above code it shows that orderline is an object of OrderlineCollection model and while you get orderlines from order model it will gives you an object of OrderlineCollection.
In order to identify what's there inside object you can iterate through it or you may print key-value from that object.
alert(orderline.forEach(function(k,v){k + " => + v}));
Or you can loop through the orderlines.
for (line in orderline){
alert(line.product_id);
}
use the get_orderlines() function to get OrderLines from particular Order.
var order = this.pos.get_order();
var products = _.map(order.get_orderlines(), function (line) {return line.product; });
console.log(products);
here i user Underscore.js for create a list of products.
you can iterate loop with products list like,
for(var i =0; i < products.length; i++)
console.log(products[i].id);

for loop in javascript to access elements incrementally

I am preparing a chart in Javascript.
I have an array element named groupedByWeek
this groupedweek is derived from JSON data. Now i am having it in form of child arrays like this: groupedByWeek = Object { 1: Array[4], 2: Array[7], 3: Array[3] }
screenshot of console is here:
Now i want to parse each of groupedByWeek elements for graph, for the following code:
function increment(){
var i = groupedByWeek[1];
barChart1.parse(i,"json");
for (; i <= groupedByWeek.length; i++){
barChart1.parse(i,"json");
}
}
and
<input type="button" onClick="increment()" value="Next"/>
but this is not working!
Infact nothing is working out inside for loop while i am doing console.log()
If i am doing like this then it's working for 1st elemnt only!!:
var i = groupedByWeek[1];
barChart1.parse(i,"json");
please give me a hint how to work it out!
You have several problems:
Your array is containing an object, not an index.
You spelt length as legnth.
You should be attempting to iterate through your object, rather than an Array. So you would do something along these lines:
Javascript:
for(var index in object) {
// Do something.
}
jQuery:
$.each(object, function(index, value) {
// Do something.
});
I believe that was your original goal, iterate your object not a collection of the items.

How to retrieve an object from a long list having a given (key,value) pair?

Hi have a long list of objects like that:
var myLongList = [
{id="1", desc:"ahahah"},
{id="2", desc:"ihihih"},
{id="3", desc:"ohohoh"},
...
{id="N", desc:"olala"}
]
I need to retrieve the object with id="14575". Since my list is quite long and I have to make a lot of such retrievals, I would prefer not to loop through the list to get my object.
So far, I use a function to index my array from a column:
function index(js, indexColumn){
var out={};
var o;
for (var key in js) {
o = js[key];
out[o[indexColumn]]=o;
}
return out;
}
A call to var myLongListIndexed = index(myLongList, "id"); builds an indexed list and myLongListIndexed["14575"] returns my beloved object.
Is there a more standard way to retrieve objects from lists based on a (key,value) pair?
Sounds like pretty much the most sensible way to do it, except that it's not a good idea to use for..in with arrays. Better to use a regular for loop or js.forEach(...).
Like this:
for (var i = 0; i < js.length; i += 1) {
o = js[i];
out[o[indexColumn]]=o;
}
or this (requires ES5):
js.forEach(function(el) {
out[el[indexColumn]] = el;
});
jQuery version (doesn't require ES5):
$.each(js, function() {
out[this[indexColumn]] = this;
});

Categories

Resources