Reputation: 255
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])
}
Upvotes: 0
Views: 42
Reputation: 678
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
Upvotes: 1