JS - object contains array name - javascript

I have the following challenge:
I have an object which contains data from internal projects. Some projects are billable and some are not.
This data is gathered from the API in Google Spreadsheets which would like to push into an array so I can display it on my sheets.
When a project [i] is not a billable project jsonObject.data[i].budget.hours.amount_budget] would not be in the object. and thefore it would return an error.
Is there a way to ask in Javascript/AppScript if the array item contains budget.hours.amount_budget for item `[i]?
Thanks in advance
var i = 0
var arrayProjectManagerName = [];
var arrayOrganizationName = [];
var arrayProjectName = [];
var arrayBudgetHoursAmountBudget = [];
var arrayBudgetHoursAmountSpent = [];
var arrayBudgetHoursValuBudget= [];
var arrayBudgetHoursValueSpent= [];
var arrayBudgetCostsValueBudget = [];
var arrayBudgetCostsValueSpent = [];
var arrayBudgetTotalValueBudget = [];
var arrayBudgetTotalValueSpent= [];
var arrayBudgetTotalValueInvoiced= [];
for (i; i < jsonObject.data.length; i++){
arrayProjectManagerName.push([jsonObject.data[i].project_manager.name])
arrayOrganizationName.push([jsonObject.data[i].organization.name])
arrayProjectName.push([jsonObject.data[i].name])
//arrayBudgetHoursAmountBudget.push([jsonObject.data[i].budget.hours.amount_budget])
//arrayBudgetHoursAmountSpent.push([jsonObject.data[i].budget.hours.amount_spent])
//arrayBudgetHoursValuBudget.push([jsonObject.data[i].budget.hours.value_budget])
//arrayBudgetHoursValueSpent.push([jsonObject.data[i].budget.hours.value_spent])
arrayBudgetCostsValueBudget.push([jsonObject.data[i].budget.costs.value_budget])
arrayBudgetCostsValueSpent.push([jsonObject.data[i].budget.costs.value_spent])
arrayBudgetTotalValueBudget.push([jsonObject.data[i].budget.total.value_budget])
arrayBudgetTotalValueSpent.push([jsonObject.data[i].budget.total.value_spent])
arrayBudgetTotalValueInvoiced.push([jsonObject.data[i].budget.total.value_invoiced])
}

You can use Object.prototype.hasOwnProperty
You can nest this in line like
jsonObject.data[i].hasOwnProperty('budget') && jsonObject.data[i].budget.hasOwnProperty('hours') && jsonObject.data[i].budget.hours.hasOwnProperty('amount_budget')
Alternatively you could make a helper function which will check deep for you to avoid repeating this logic again and again
hasProperty = (obj, property) => {
if(!property){
return true;
}
let props = property.split('.');
return obj.hasOwnProperty(props[0]) && hasProperty(obj[props[0]], props.splice(1).join('.'));
}
You can find further suggestions in this SO question

Related

SCRIPT28: Out of stack space

Getting stack out of space in IE 10,11 when I try encode a array of data to Json and store it into an array
var SelPeriod = Ext.getCmp('SelectedPeriodGrid');
SelPerioddata = [];
var PeriodsSelected = SelPeriod.getStore('MarkettrackDrillDownPeriods').getRange();
for (var i = 0; i < PeriodsSelected.length; i++) {
SelPerioddata.push(PeriodsSelected[i]);
}
var SelPerioddatajson = [];
SelPerioddatajson = Ext.JSON.encod(SelPerioddata);
Try using only the record's data, like:
SelPerioddata.push(PeriodsSelected[i].data);
You can also rewrite this like:
var selPeriod = Ext.getCmp('SelectedPeriodGrid'),
periodsSelected = selPeriod.getStore('MarkettrackDrillDownPeriods').getRange(),
selPerioddatajson = Ext.JSON.encode(periodsSelected.map(function(record) {
return record.data;
}));

Issue with javascript array variables

I am using javascript in my app which is a rhino javascript engine. I like to use array for an array.
The following code is my actual working code.
while (input.hasNext()) {
var data = input.next();
var new_data = {};
var i = 0;
while(i<data.get('total_entries')){
new_data.entries = data.get('total_entries');
new_data.id = data.get('out').get(i).get('id');
output.write(new_data);
i++;
}
}
I need to create array for new_data[].
while (input.hasNext()) {
var data = input.next();
var new_data[] = {};
var i = 0;
while(i<data.get('total_entries')){
new_data[i].entries = data.get('total_entries');
new_data[i].id = data.get('out').get(i).get('id');
output.write(new_data[i]);
i++;
}
}
But its not working. So, help me to create array variable in it.
Thanks.
You mean something like this:
while (input.hasNext()) {
var data = input.next();
var new_data = [];
var i = 0;
while(i<data.get('total_entries')){
new_data.push({entries: data.get('total_entries'), id: data.get('out').get(i).get('id')});
output.write(new_data[i]);
i++;
}
}
var new_data[] = {};
First of all, that's invalid JavaScript.
new_data[i]
Looks like you want new_data to be an array of objects. Why not declare it as one and add objects on every iteration of the while loop:
var new_data = [];
while(...){
new_data.push({
entries: ...
id: ...
});
}

array object manipulation to create new object

var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var expect = [
{month:"JAN",val: {"UK":"24","AUSTRIA":"64","ITALY":"21"}},
{month:"FEB",val: {"UK":"14","AUSTRIA":"24","ITALY":"22"}},
{month:"MAR",val: {"UK":"56","AUSTRIA":"24","ITALY":"51"}}
];
I have array of objects which i need to reshape for one other work. need some manipulation which will convert by one function. I have created plunker https://jsbin.com/himawakaju/edit?html,js,console,output
Main factors are Month, Country and its "AC" value.
Loop through, make an object and than loop through to make your array
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var outTemp = {};
actual.forEach(function(obj){ //loop through array
//see if we saw the month already, if not create it
if(!outTemp[obj.month]) outTemp[obj.month] = { month : obj.month, val: {} };
outTemp[obj.month].val[obj.country] = obj.AC; //add the country with value
});
var expected = []; //convert the object to the array format that was expected
for (var p in outTemp) {
expected.push(outTemp[p]);
}
console.log(expected);
Iterate through array and create new list
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var newList =[], val;
for(var i=0; i < actual.length; i+=3){
val = {};
val[actual[i].country] = actual[i]["AC"];
val[actual[i+1].country] = actual[i+1]["AC"];
val[actual[i+2].country] = actual[i+2]["AC"];
newList.push({month: actual[i].month, val:val})
}
document.body.innerHTML = JSON.stringify(newList);
This is the correct code... as above solution will help you if there are 3 rows and these will be in same sequnece.
Here is perfect solution :
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var tmpArray = [];
var obj =[];
for(var k=0; k<actual.length; k++){
var position = tmpArray.indexOf(actual[k].month);
if(position == -1){
tmpArray.push(actual[k].month);
val = {};
for(var i=0; i<actual.length; i++){
if(actual[i].month == actual[k].month){
val[actual[i].country] = actual[i]["AC"];
}
}
obj.push({month: actual[k].month, val:val});
}
}

How to extract values from an array of arrays in Javascript?

I have a variable as follows:
var dataset = {
"towns": [
["Aladağ", "Adana", [35.4,37.5], [0]],
["Ceyhan", "Adana", [35.8,37], [0]],
["Feke", "Adana", [35.9,37.8], [0]]
]
};
The variable has a lot of town data in it. How can I extract the first elements of the third ones from the data efficiently? I,e, what will ... be below?
var myArray = ...
//myArray == [35.4,35.8,35.9] for the given data
And what to do if I want to store both values in the array? That is
var myArray = ...
//myArray == [[35.4,37.5], [35.8,37], [35.9,37.8]] for the given data
I'm very new to Javascript. I hope there's a way without using for loops.
On newer browsers, you can use map, or forEach which would avoid using a for loop.
var myArray = dataset.towns.map(function(town){
return town[2];
});
// myArray == [[35.4,37.5], [35.8,37], [35.9,37.8]]
But for loops are more compatible.
var myArray = [];
for(var i = 0, len = dataset.towns.length; i < len; i++){
myArray.push(dataset.towns[i][2];
}
Impossible without loops:
var myArray = [];
for (var i = 0; i < dataset.towns.length; i++) {
myArray.push(dataset.towns[i][2][0]);
}
// at this stage myArray = [35.4, 35.8, 35.9]
And what to do if I want to store both values in the array?
Similar, you just add the entire array, not only the first element:
var myArray = [];
for (var i = 0; i < dataset.towns.length; i++) {
myArray.push(dataset.towns[i][2]);
}
// at this stage myArray = [[35.4,37.5], [35.8,37], [35.9,37.8]]

How to combine these two JavaScript arrays

I have two JavaScript arrays below that both have the same number of entries, but that number can vary.
[{"branchids":"5006"},{"branchids":"5007"},{"branchids":"5009"}]
[{"branchnames":"GrooveToyota"},{"branchnames":"GrooveSubaru"},{"branchnames":"GrooveFord"}]
I want to combine these two arrays so that I get
[{"5006":"GrooveToyota"},{"5007":"GrooveSubaru"},{"5008":"GrooveFord"}]
I'm not sure how to put it into words but hopefully someone understands. I would like to do this with two arrays of arbitrary length (both the same length though).
Any tips appreciated.
It's kind of a zip:
function zip(a, b) {
var len = Math.min(a.length, b.length),
zipped = [],
i, obj;
for (i = 0; i < len; i++) {
obj= {};
obj[a[i].branchids] = b[i].branchnames;
zipped.push(obj);
}
return zipped;
}
Example (uses console.log ie users)
var ids = [{"branchids":"5006"},{"branchids":"5007"},{"branchids":"5009"}];
var names = [{"branchnames":"GrooveToyota"},{"branchnames":"GrooveSubaru"},{"branchnames":"GrooveFord"}];
var combined = [];
for (var i = 0; i < ids.length; i++) {
var combinedObject = {};
combinedObject[ids[i].branchids] = names[i].branchnames;
combined.push(combinedObject);
}
combined; // [{"5006":"GrooveToyota"},{"5006":"GrooveSubaru"},{"5006":"GrooveFord"}]
Personally, I would do it IAbstractDownvoteFactor's way (+1), but for another option, I present the following for your coding pleasure:
var a = [{"branchids":"5006"},{"branchids":"5007"},{"branchids":"5009"}];
var b = [{"branchnames":"GrooveToyota"},{"branchnames":"GrooveSubaru"},{"branchnames":"GrooveFord"}];
var zipped = a.map(function(o,i){ var n={};n[o.branchids]=b[i].branchnames;return n;});
similar to #robert solution but using Array.prototype.map
var ids = [{"branchids":"5006"},{"branchids":"5007"},{"branchids":"5009"}],
names = [{"branchnames":"GrooveToyota"},{"branchnames":"GrooveSubaru"},{"branchnames":"GrooveFord"}],
merged = ids.map(function (o, i) { var obj = {}; obj[o.branchids]=names[i].branchnames; return obj; });
merged; //[{5006: "GrooveToyota"}, {5006: "GrooveSubaru"}, {5006:"GrooveFord"}]
Cheers!

Categories

Resources