suggest me the different options to store this data in javascript - javascript

I am getting the data in the following format
[Sl.No, Amount, Transaction Type, Account Number]
[01, $10000, Deposit, 473882829]
[02, $10202, Deposit, 348844844]
[02, $10202, Withdrawal, 348844844]
What is the best way to store this data in Javascript for faster retrieval

var data = ["02", "$10202", "Withdrawal", 348844844]
//empty object
var list = {};
//Constructing the index by concatenating the last two elements of the data.
//Probably this will give the primary key to the data.
var index = data[2] + data[3].toString();
//Store the data using the index
list[index] = data;
You can retrieve the data using the index constructed above.

Determine how the data needs to be accessed. I am guessing it needs to be accessed linearly, so as to not accidentally overdraw (withdraw before deposit), etc -- in this case an Array is generally a suitable data structure. A simple for-loop should be able to find most simple "queries".
Define how the object is represented in Javascript -- is each "transaction item" an array of [x, amount, type, account] or is it an object with the signature {x: ..., amount: ..., type: ..., account: ...} (I often opt for the latter as it adds some self-documentation). It could also be an object created with new TransactionItem (or whatnot) that includes methods.
Determine how to convert the raw data into the chosen object representation. For a well-defined format a simple regular expression or 'split' may work.
Use data. Remember that even a shoddy O(n^2) algorithm is generally "fast enough" for small n. Best to get it working first.
Happy coding.

Related

In a JSON object, how do I retrieve values of objects within a JSON object without knowing the key?

In the following API response, I have an object of time_entries, each having an ID as a key.
{"count":5,"results":[{"key":"time_entries","id":"1522040735"},{"key":"time_entries","id":"1522040395"},{"key":"time_entries","id":"1517855265"},{"key":"time_entries","id":"1517854385"},{"key":"time_entries","id":"1517853315"}],"time_entries":{"1522040735":{"created_at":"2020-06-22T13:54:54-07:00","updated_at":"2020-06-22T13:54:54-07:00","date_performed":"2020-06-22","time_in_minutes":75,"billable":true,"notes":"","rate_in_cents":25000,"cost_rate_in_cents":null,"currency":"USD","currency_symbol":"$","currency_base_unit":100,"user_can_edit":false,"approved":false,"taxable":false,"is_invoiced":true,"story_id":"569297425","workspace_id":"31689165","user_id":"13403745","active_submission_id":null,"recent_submission_id":null,"id":"1522040735"},"1522040395":{"created_at":"2020-06-22T13:54:42-07:00","updated_at":"2020-06-22T13:54:42-07:00","date_performed":"2020-06-22","time_in_minutes":90,"billable":true,"notes":"","rate_in_cents":25000,"cost_rate_in_cents":null,"currency":"USD","currency_symbol":"$","currency_base_unit":100,"user_can_edit":false,"approved":false,"taxable":false,"is_invoiced":true,"story_id":"569297345","workspace_id":"31689165","user_id":"13403745","active_submission_id":null,"recent_submission_id":null,"id":"1522040395"},"1517855265":{"created_at":"2020-06-19T10:32:50-07:00","updated_at":"2020-06-19T10:32:50-07:00","date_performed":"2020-06-19","time_in_minutes":60,"billable":true,"notes":"","rate_in_cents":25000,"cost_rate_in_cents":null,"currency":"USD","currency_symbol":"$","currency_base_unit":100,"user_can_edit":false,"approved":false,"taxable":false,"is_invoiced":true,"story_id":"568676695","workspace_id":"31689165","user_id":"13403745","active_submission_id":null,"recent_submission_id":null,"id":"1517855265"},"1517854385":{"created_at":"2020-06-19T10:32:12-07:00","updated_at":"2020-06-19T10:32:12-07:00","date_performed":"2020-06-19","time_in_minutes":120,"billable":true,"notes":"","rate_in_cents":25000,"cost_rate_in_cents":null,"currency":"USD","currency_symbol":"$","currency_base_unit":100,"user_can_edit":false,"approved":false,"taxable":false,"is_invoiced":true,"story_id":"568676755","workspace_id":"31689165","user_id":"13403745","active_submission_id":null,"recent_submission_id":null,"id":"1517854385"},"1517853315":{"created_at":"2020-06-19T10:31:40-07:00","updated_at":"2020-06-19T10:31:40-07:00","date_performed":"2020-06-19","time_in_minutes":180,"billable":true,"notes":"","rate_in_cents":25000,"cost_rate_in_cents":null,"currency":"USD","currency_symbol":"$","currency_base_unit":100,"user_can_edit":false,"approved":false,"taxable":false,"is_invoiced":true,"story_id":"568676765","workspace_id":"31689165","user_id":"13403745","active_submission_id":null,"recent_submission_id":null,"id":"1517853315"}},"meta":{"count":5,"page_count":1,"page_number":1,"page_size":20},"stories":{"569297425":{"title":"task5","description":"task5desc","updated_at":"2020-06-22T13:56:41-07:00","assignment_timestamped_at":"2020-06-22T13:56:41-07:00","created_at":"2020-06-22T13:54:08-07:00","due_date":null,"start_date":null,"story_type":"task","state":"started","position":99960000,"archived":false,"deleted_at":null,"sub_story_count":0,"percentage_complete":0,"priority":"normal","has_proofing_access":false,"ancestor_ids":[],"subtree_depth":0,"ancestry_depth":0,"time_trackable":true,"time_estimate_in_minutes":null,"logged_billable_time_in_minutes":75,"logged_nonbillable_time_in_minutes":0,"sub_stories_time_estimate_in_minutes":null,"sub_stories_billable_time_in_minutes":null,"weight":null,"budget_estimate_in_cents":null,"budget_used_in_cents":31250,"uninvoiced_balance_in_cents":0,"invoiced_balance_in_cents":31250,"sub_stories_budget_estimate_in_cents":null,"sub_stories_budget_used_in_cents":null,"fixed_fee":false,"billable":true,"workspace_id":"31689165","creator_id":"13403745","parent_id":null,"root_id":null,"id":"569297425"},"569297345":{"title":"task4","description":"task4desc","updated_at":"2020-06-22T13:56:41-07:00","assignment_timestamped_at":"2020-06-22T13:56:41-07:00","created_at":"2020-06-22T13:53:55-07:00","due_date":null,"start_date":null,"story_type":"task","state":"started","position":99970000,"archived":false,"deleted_at":null,"sub_story_count":0,"percentage_complete":0,"priority":"normal","has_proofing_access":false,"ancestor_ids":[],"subtree_depth":0,"ancestry_depth":0,"time_trackable":true,"time_estimate_in_minutes":null,"logged_billable_time_in_minutes":90,"logged_nonbillable_time_in_minutes":0,"sub_stories_time_estimate_in_minutes":null,"sub_stories_billable_time_in_minutes":null,"weight":null,"budget_estimate_in_cents":null,"budget_used_in_cents":37500,"uninvoiced_balance_in_cents":0,"invoiced_balance_in_cents":37500,"sub_stories_budget_estimate_in_cents":null,"sub_stories_budget_used_in_cents":null,"fixed_fee":false,"billable":true,"workspace_id":"31689165","creator_id":"13403745","parent_id":null,"root_id":null,"id":"569297345"},"568676695":{"title":"task1","description":"desc1","updated_at":"2020-06-22T13:56:40-07:00","assignment_timestamped_at":"2020-06-22T13:56:40-07:00","created_at":"2020-06-19T10:26:09-07:00","due_date":null,"start_date":"2020-06-19","story_type":"task","state":"completed","position":100000000,"archived":false,"deleted_at":null,"sub_story_count":0,"percentage_complete":100,"priority":"normal","has_proofing_access":false,"ancestor_ids":[],"subtree_depth":0,"ancestry_depth":0,"time_trackable":true,"time_estimate_in_minutes":120,"logged_billable_time_in_minutes":60,"logged_nonbillable_time_in_minutes":0,"sub_stories_time_estimate_in_minutes":null,"sub_stories_billable_time_in_minutes":null,"weight":null,"budget_estimate_in_cents":10000,"budget_used_in_cents":30000,"uninvoiced_balance_in_cents":0,"invoiced_balance_in_cents":30000,"sub_stories_budget_estimate_in_cents":null,"sub_stories_budget_used_in_cents":null,"fixed_fee":false,"billable":true,"workspace_id":"31689165","creator_id":"13403745","parent_id":null,"root_id":null,"id":"568676695"},"568676755":{"title":"task2","description":"desc2","updated_at":"2020-06-22T13:56:40-07:00","assignment_timestamped_at":"2020-06-22T13:56:40-07:00","created_at":"2020-06-19T10:26:27-07:00","due_date":null,"start_date":"2020-06-19","story_type":"task","state":"completed","position":99990000,"archived":false,"deleted_at":null,"sub_story_count":0,"percentage_complete":100,"priority":"normal","has_proofing_access":false,"ancestor_ids":[],"subtree_depth":0,"ancestry_depth":0,"time_trackable":true,"time_estimate_in_minutes":120,"logged_billable_time_in_minutes":120,"logged_nonbillable_time_in_minutes":0,"sub_stories_time_estimate_in_minutes":null,"sub_stories_billable_time_in_minutes":null,"weight":null,"budget_estimate_in_cents":20000,"budget_used_in_cents":50000,"uninvoiced_balance_in_cents":0,"invoiced_balance_in_cents":50000,"sub_stories_budget_estimate_in_cents":null,"sub_stories_budget_used_in_cents":null,"fixed_fee":false,"billable":true,"workspace_id":"31689165","creator_id":"13403745","parent_id":null,"root_id":null,"id":"568676755"},"568676765":{"title":"task3","description":"desc3","updated_at":"2020-06-22T13:56:40-07:00","assignment_timestamped_at":"2020-06-22T13:56:40-07:00","created_at":"2020-06-19T10:26:36-07:00","due_date":null,"start_date":"2020-06-19","story_type":"task","state":"completed","position":99980000,"archived":false,"deleted_at":null,"sub_story_count":0,"percentage_complete":100,"priority":"normal","has_proofing_access":false,"ancestor_ids":[],"subtree_depth":0,"ancestry_depth":0,"time_trackable":true,"time_estimate_in_minutes":180,"logged_billable_time_in_minutes":180,"logged_nonbillable_time_in_minutes":0,"sub_stories_time_estimate_in_minutes":null,"sub_stories_billable_time_in_minutes":null,"weight":null,"budget_estimate_in_cents":30000,"budget_used_in_cents":75000,"uninvoiced_balance_in_cents":0,"invoiced_balance_in_cents":75000,"sub_stories_budget_estimate_in_cents":null,"sub_stories_budget_used_in_cents":null,"fixed_fee":false,"billable":true,"workspace_id":"31689165","creator_id":"13403745","parent_id":null,"root_id":null,"id":"568676765"}}}
Problem is, for every API call, I won't know what that time entry ID is. It will change every time.
What I want to do is to capture a string output of a specific key inside each of those time entry objects.
For example, for time_in_minutes, what I need to capture in this case is: "75, 90, 60, 120, 180"
And I also need it to be in that format, regardless of how many entries there are—whether there are five entries or twenty.
Any tips or advice would be GREATLY appreciated.
I'm not sure if this is the most elegant or performant solution, but I think this produces the correct values:
//copied from the question
const apiResponse = {"count":5,"results":[{"key":"time_entries","id":"1522040735"},{"key":"time_entries","id":"1522040395"},{"key":"time_entries","id":"1517855265"},{"key":"time_entries","id":"1517854385"},{"key":"time_entries","id":"1517853315"}],"time_entries":{"1522040735":{"created_at":"2020-06-22T13:54:54-07:00","updated_at":"2020-06-22T13:54:54-07:00","date_performed":"2020-06-22","time_in_minutes":75,"billable":true,"notes":"","rate_in_cents":25000,"cost_rate_in_cents":null,"currency":"USD","currency_symbol":"$","currency_base_unit":100,"user_can_edit":false,"approved":false,"taxable":false,"is_invoiced":true,"story_id":"569297425","workspace_id":"31689165","user_id":"13403745","active_submission_id":null,"recent_submission_id":null,"id":"1522040735"},"1522040395":{"created_at":"2020-06-22T13:54:42-07:00","updated_at":"2020-06-22T13:54:42-07:00","date_performed":"2020-06-22","time_in_minutes":90,"billable":true,"notes":"","rate_in_cents":25000,"cost_rate_in_cents":null,"currency":"USD","currency_symbol":"$","currency_base_unit":100,"user_can_edit":false,"approved":false,"taxable":false,"is_invoiced":true,"story_id":"569297345","workspace_id":"31689165","user_id":"13403745","active_submission_id":null,"recent_submission_id":null,"id":"1522040395"},"1517855265":{"created_at":"2020-06-19T10:32:50-07:00","updated_at":"2020-06-19T10:32:50-07:00","date_performed":"2020-06-19","time_in_minutes":60,"billable":true,"notes":"","rate_in_cents":25000,"cost_rate_in_cents":null,"currency":"USD","currency_symbol":"$","currency_base_unit":100,"user_can_edit":false,"approved":false,"taxable":false,"is_invoiced":true,"story_id":"568676695","workspace_id":"31689165","user_id":"13403745","active_submission_id":null,"recent_submission_id":null,"id":"1517855265"},"1517854385":{"created_at":"2020-06-19T10:32:12-07:00","updated_at":"2020-06-19T10:32:12-07:00","date_performed":"2020-06-19","time_in_minutes":120,"billable":true,"notes":"","rate_in_cents":25000,"cost_rate_in_cents":null,"currency":"USD","currency_symbol":"$","currency_base_unit":100,"user_can_edit":false,"approved":false,"taxable":false,"is_invoiced":true,"story_id":"568676755","workspace_id":"31689165","user_id":"13403745","active_submission_id":null,"recent_submission_id":null,"id":"1517854385"},"1517853315":{"created_at":"2020-06-19T10:31:40-07:00","updated_at":"2020-06-19T10:31:40-07:00","date_performed":"2020-06-19","time_in_minutes":180,"billable":true,"notes":"","rate_in_cents":25000,"cost_rate_in_cents":null,"currency":"USD","currency_symbol":"$","currency_base_unit":100,"user_can_edit":false,"approved":false,"taxable":false,"is_invoiced":true,"story_id":"568676765","workspace_id":"31689165","user_id":"13403745","active_submission_id":null,"recent_submission_id":null,"id":"1517853315"}},"meta":{"count":5,"page_count":1,"page_number":1,"page_size":20},"stories":{"569297425":{"title":"task5","description":"task5desc","updated_at":"2020-06-22T13:56:41-07:00","assignment_timestamped_at":"2020-06-22T13:56:41-07:00","created_at":"2020-06-22T13:54:08-07:00","due_date":null,"start_date":null,"story_type":"task","state":"started","position":99960000,"archived":false,"deleted_at":null,"sub_story_count":0,"percentage_complete":0,"priority":"normal","has_proofing_access":false,"ancestor_ids":[],"subtree_depth":0,"ancestry_depth":0,"time_trackable":true,"time_estimate_in_minutes":null,"logged_billable_time_in_minutes":75,"logged_nonbillable_time_in_minutes":0,"sub_stories_time_estimate_in_minutes":null,"sub_stories_billable_time_in_minutes":null,"weight":null,"budget_estimate_in_cents":null,"budget_used_in_cents":31250,"uninvoiced_balance_in_cents":0,"invoiced_balance_in_cents":31250,"sub_stories_budget_estimate_in_cents":null,"sub_stories_budget_used_in_cents":null,"fixed_fee":false,"billable":true,"workspace_id":"31689165","creator_id":"13403745","parent_id":null,"root_id":null,"id":"569297425"},"569297345":{"title":"task4","description":"task4desc","updated_at":"2020-06-22T13:56:41-07:00","assignment_timestamped_at":"2020-06-22T13:56:41-07:00","created_at":"2020-06-22T13:53:55-07:00","due_date":null,"start_date":null,"story_type":"task","state":"started","position":99970000,"archived":false,"deleted_at":null,"sub_story_count":0,"percentage_complete":0,"priority":"normal","has_proofing_access":false,"ancestor_ids":[],"subtree_depth":0,"ancestry_depth":0,"time_trackable":true,"time_estimate_in_minutes":null,"logged_billable_time_in_minutes":90,"logged_nonbillable_time_in_minutes":0,"sub_stories_time_estimate_in_minutes":null,"sub_stories_billable_time_in_minutes":null,"weight":null,"budget_estimate_in_cents":null,"budget_used_in_cents":37500,"uninvoiced_balance_in_cents":0,"invoiced_balance_in_cents":37500,"sub_stories_budget_estimate_in_cents":null,"sub_stories_budget_used_in_cents":null,"fixed_fee":false,"billable":true,"workspace_id":"31689165","creator_id":"13403745","parent_id":null,"root_id":null,"id":"569297345"},"568676695":{"title":"task1","description":"desc1","updated_at":"2020-06-22T13:56:40-07:00","assignment_timestamped_at":"2020-06-22T13:56:40-07:00","created_at":"2020-06-19T10:26:09-07:00","due_date":null,"start_date":"2020-06-19","story_type":"task","state":"completed","position":100000000,"archived":false,"deleted_at":null,"sub_story_count":0,"percentage_complete":100,"priority":"normal","has_proofing_access":false,"ancestor_ids":[],"subtree_depth":0,"ancestry_depth":0,"time_trackable":true,"time_estimate_in_minutes":120,"logged_billable_time_in_minutes":60,"logged_nonbillable_time_in_minutes":0,"sub_stories_time_estimate_in_minutes":null,"sub_stories_billable_time_in_minutes":null,"weight":null,"budget_estimate_in_cents":10000,"budget_used_in_cents":30000,"uninvoiced_balance_in_cents":0,"invoiced_balance_in_cents":30000,"sub_stories_budget_estimate_in_cents":null,"sub_stories_budget_used_in_cents":null,"fixed_fee":false,"billable":true,"workspace_id":"31689165","creator_id":"13403745","parent_id":null,"root_id":null,"id":"568676695"},"568676755":{"title":"task2","description":"desc2","updated_at":"2020-06-22T13:56:40-07:00","assignment_timestamped_at":"2020-06-22T13:56:40-07:00","created_at":"2020-06-19T10:26:27-07:00","due_date":null,"start_date":"2020-06-19","story_type":"task","state":"completed","position":99990000,"archived":false,"deleted_at":null,"sub_story_count":0,"percentage_complete":100,"priority":"normal","has_proofing_access":false,"ancestor_ids":[],"subtree_depth":0,"ancestry_depth":0,"time_trackable":true,"time_estimate_in_minutes":120,"logged_billable_time_in_minutes":120,"logged_nonbillable_time_in_minutes":0,"sub_stories_time_estimate_in_minutes":null,"sub_stories_billable_time_in_minutes":null,"weight":null,"budget_estimate_in_cents":20000,"budget_used_in_cents":50000,"uninvoiced_balance_in_cents":0,"invoiced_balance_in_cents":50000,"sub_stories_budget_estimate_in_cents":null,"sub_stories_budget_used_in_cents":null,"fixed_fee":false,"billable":true,"workspace_id":"31689165","creator_id":"13403745","parent_id":null,"root_id":null,"id":"568676755"},"568676765":{"title":"task3","description":"desc3","updated_at":"2020-06-22T13:56:40-07:00","assignment_timestamped_at":"2020-06-22T13:56:40-07:00","created_at":"2020-06-19T10:26:36-07:00","due_date":null,"start_date":"2020-06-19","story_type":"task","state":"completed","position":99980000,"archived":false,"deleted_at":null,"sub_story_count":0,"percentage_complete":100,"priority":"normal","has_proofing_access":false,"ancestor_ids":[],"subtree_depth":0,"ancestry_depth":0,"time_trackable":true,"time_estimate_in_minutes":180,"logged_billable_time_in_minutes":180,"logged_nonbillable_time_in_minutes":0,"sub_stories_time_estimate_in_minutes":null,"sub_stories_billable_time_in_minutes":null,"weight":null,"budget_estimate_in_cents":30000,"budget_used_in_cents":75000,"uninvoiced_balance_in_cents":0,"invoiced_balance_in_cents":75000,"sub_stories_budget_estimate_in_cents":null,"sub_stories_budget_used_in_cents":null,"fixed_fee":false,"billable":true,"workspace_id":"31689165","creator_id":"13403745","parent_id":null,"root_id":null,"id":"568676765"}}}
const timeEntries = apiResponse['time_entries'];
const minuteTimes = Object.values(timeEntries).map(entry => entry['time_in_minutes']);
//prints [180, 120, 60, 90, 75]
console.log(minuteTimes);
If you need to filter the time_entries by id (if you want to look at a subset, for instance) then you can probably incorporate this
Let's define response to hold the API return, and what is the
property you wish to extract from each time_entries object.
function extract(response, what){
const parsed = (typeof(response)==='object')? response: JSON.parse(response);
return (Object
.keys(parsed.time_entries) // finds the keys
.sort((a,b)=>(+b-a)) // sorts the keys in reverse order
.map((k)=>(parsed.time_entries[k][what])) // finds the data
.filter((v)=>(v!==undefined)) // removes undefined data
.join(",") // changes to CSV [75,90,60,...] -> '75,90,60,...'
);
}
Testing in node.js
extract(response, 'time_in_minutes');
'75,90,60,120,180'
Try,
Object.keys() method on the object.
you can use Object.values to get the values of each key and do the map iteration for the specific result.
var resp = {"count":5,"results":[{"key":"time_entries","id":"1522040735"},{"key":"time_entries","id":"1522040395"},{"key":"time_entries","id":"1517855265"},{"key":"time_entries","id":"1517854385"},{"key":"time_entries","id":"1517853315"}],"time_entries":{"1522040735":{"created_at":"2020-06-22T13:54:54-07:00","updated_at":"2020-06-22T13:54:54-07:00","date_performed":"2020-06-22","time_in_minutes":75,"billable":true,"notes":"","rate_in_cents":25000,"cost_rate_in_cents":null,"currency":"USD","currency_symbol":"$","currency_base_unit":100,"user_can_edit":false,"approved":false,"taxable":false,"is_invoiced":true,"story_id":"569297425","workspace_id":"31689165","user_id":"13403745","active_submission_id":null,"recent_submission_id":null,"id":"1522040735"},"1522040395":{"created_at":"2020-06-22T13:54:42-07:00","updated_at":"2020-06-22T13:54:42-07:00","date_performed":"2020-06-22","time_in_minutes":90,"billable":true,"notes":"","rate_in_cents":25000,"cost_rate_in_cents":null,"currency":"USD","currency_symbol":"$","currency_base_unit":100,"user_can_edit":false,"approved":false,"taxable":false,"is_invoiced":true,"story_id":"569297345","workspace_id":"31689165","user_id":"13403745","active_submission_id":null,"recent_submission_id":null,"id":"1522040395"},"1517855265":{"created_at":"2020-06-19T10:32:50-07:00","updated_at":"2020-06-19T10:32:50-07:00","date_performed":"2020-06-19","time_in_minutes":60,"billable":true,"notes":"","rate_in_cents":25000,"cost_rate_in_cents":null,"currency":"USD","currency_symbol":"$","currency_base_unit":100,"user_can_edit":false,"approved":false,"taxable":false,"is_invoiced":true,"story_id":"568676695","workspace_id":"31689165","user_id":"13403745","active_submission_id":null,"recent_submission_id":null,"id":"1517855265"},"1517854385":{"created_at":"2020-06-19T10:32:12-07:00","updated_at":"2020-06-19T10:32:12-07:00","date_performed":"2020-06-19","time_in_minutes":120,"billable":true,"notes":"","rate_in_cents":25000,"cost_rate_in_cents":null,"currency":"USD","currency_symbol":"$","currency_base_unit":100,"user_can_edit":false,"approved":false,"taxable":false,"is_invoiced":true,"story_id":"568676755","workspace_id":"31689165","user_id":"13403745","active_submission_id":null,"recent_submission_id":null,"id":"1517854385"},"1517853315":{"created_at":"2020-06-19T10:31:40-07:00","updated_at":"2020-06-19T10:31:40-07:00","date_performed":"2020-06-19","time_in_minutes":180,"billable":true,"notes":"","rate_in_cents":25000,"cost_rate_in_cents":null,"currency":"USD","currency_symbol":"$","currency_base_unit":100,"user_can_edit":false,"approved":false,"taxable":false,"is_invoiced":true,"story_id":"568676765","workspace_id":"31689165","user_id":"13403745","active_submission_id":null,"recent_submission_id":null,"id":"1517853315"}},"meta":{"count":5,"page_count":1,"page_number":1,"page_size":20},"stories":{"569297425":{"title":"task5","description":"task5desc","updated_at":"2020-06-22T13:56:41-07:00","assignment_timestamped_at":"2020-06-22T13:56:41-07:00","created_at":"2020-06-22T13:54:08-07:00","due_date":null,"start_date":null,"story_type":"task","state":"started","position":99960000,"archived":false,"deleted_at":null,"sub_story_count":0,"percentage_complete":0,"priority":"normal","has_proofing_access":false,"ancestor_ids":[],"subtree_depth":0,"ancestry_depth":0,"time_trackable":true,"time_estimate_in_minutes":null,"logged_billable_time_in_minutes":75,"logged_nonbillable_time_in_minutes":0,"sub_stories_time_estimate_in_minutes":null,"sub_stories_billable_time_in_minutes":null,"weight":null,"budget_estimate_in_cents":null,"budget_used_in_cents":31250,"uninvoiced_balance_in_cents":0,"invoiced_balance_in_cents":31250,"sub_stories_budget_estimate_in_cents":null,"sub_stories_budget_used_in_cents":null,"fixed_fee":false,"billable":true,"workspace_id":"31689165","creator_id":"13403745","parent_id":null,"root_id":null,"id":"569297425"},"569297345":{"title":"task4","description":"task4desc","updated_at":"2020-06-22T13:56:41-07:00","assignment_timestamped_at":"2020-06-22T13:56:41-07:00","created_at":"2020-06-22T13:53:55-07:00","due_date":null,"start_date":null,"story_type":"task","state":"started","position":99970000,"archived":false,"deleted_at":null,"sub_story_count":0,"percentage_complete":0,"priority":"normal","has_proofing_access":false,"ancestor_ids":[],"subtree_depth":0,"ancestry_depth":0,"time_trackable":true,"time_estimate_in_minutes":null,"logged_billable_time_in_minutes":90,"logged_nonbillable_time_in_minutes":0,"sub_stories_time_estimate_in_minutes":null,"sub_stories_billable_time_in_minutes":null,"weight":null,"budget_estimate_in_cents":null,"budget_used_in_cents":37500,"uninvoiced_balance_in_cents":0,"invoiced_balance_in_cents":37500,"sub_stories_budget_estimate_in_cents":null,"sub_stories_budget_used_in_cents":null,"fixed_fee":false,"billable":true,"workspace_id":"31689165","creator_id":"13403745","parent_id":null,"root_id":null,"id":"569297345"},"568676695":{"title":"task1","description":"desc1","updated_at":"2020-06-22T13:56:40-07:00","assignment_timestamped_at":"2020-06-22T13:56:40-07:00","created_at":"2020-06-19T10:26:09-07:00","due_date":null,"start_date":"2020-06-19","story_type":"task","state":"completed","position":100000000,"archived":false,"deleted_at":null,"sub_story_count":0,"percentage_complete":100,"priority":"normal","has_proofing_access":false,"ancestor_ids":[],"subtree_depth":0,"ancestry_depth":0,"time_trackable":true,"time_estimate_in_minutes":120,"logged_billable_time_in_minutes":60,"logged_nonbillable_time_in_minutes":0,"sub_stories_time_estimate_in_minutes":null,"sub_stories_billable_time_in_minutes":null,"weight":null,"budget_estimate_in_cents":10000,"budget_used_in_cents":30000,"uninvoiced_balance_in_cents":0,"invoiced_balance_in_cents":30000,"sub_stories_budget_estimate_in_cents":null,"sub_stories_budget_used_in_cents":null,"fixed_fee":false,"billable":true,"workspace_id":"31689165","creator_id":"13403745","parent_id":null,"root_id":null,"id":"568676695"},"568676755":{"title":"task2","description":"desc2","updated_at":"2020-06-22T13:56:40-07:00","assignment_timestamped_at":"2020-06-22T13:56:40-07:00","created_at":"2020-06-19T10:26:27-07:00","due_date":null,"start_date":"2020-06-19","story_type":"task","state":"completed","position":99990000,"archived":false,"deleted_at":null,"sub_story_count":0,"percentage_complete":100,"priority":"normal","has_proofing_access":false,"ancestor_ids":[],"subtree_depth":0,"ancestry_depth":0,"time_trackable":true,"time_estimate_in_minutes":120,"logged_billable_time_in_minutes":120,"logged_nonbillable_time_in_minutes":0,"sub_stories_time_estimate_in_minutes":null,"sub_stories_billable_time_in_minutes":null,"weight":null,"budget_estimate_in_cents":20000,"budget_used_in_cents":50000,"uninvoiced_balance_in_cents":0,"invoiced_balance_in_cents":50000,"sub_stories_budget_estimate_in_cents":null,"sub_stories_budget_used_in_cents":null,"fixed_fee":false,"billable":true,"workspace_id":"31689165","creator_id":"13403745","parent_id":null,"root_id":null,"id":"568676755"},"568676765":{"title":"task3","description":"desc3","updated_at":"2020-06-22T13:56:40-07:00","assignment_timestamped_at":"2020-06-22T13:56:40-07:00","created_at":"2020-06-19T10:26:36-07:00","due_date":null,"start_date":"2020-06-19","story_type":"task","state":"completed","position":99980000,"archived":false,"deleted_at":null,"sub_story_count":0,"percentage_complete":100,"priority":"normal","has_proofing_access":false,"ancestor_ids":[],"subtree_depth":0,"ancestry_depth":0,"time_trackable":true,"time_estimate_in_minutes":180,"logged_billable_time_in_minutes":180,"logged_nonbillable_time_in_minutes":0,"sub_stories_time_estimate_in_minutes":null,"sub_stories_billable_time_in_minutes":null,"weight":null,"budget_estimate_in_cents":30000,"budget_used_in_cents":75000,"uninvoiced_balance_in_cents":0,"invoiced_balance_in_cents":75000,"sub_stories_budget_estimate_in_cents":null,"sub_stories_budget_used_in_cents":null,"fixed_fee":false,"billable":true,"workspace_id":"31689165","creator_id":"13403745","parent_id":null,"root_id":null,"id":"568676765"}}}
var output = Object.values(resp.time_entries).map(val => val.time_in_minutes).join(',');
console.log(output);

Extracting data fields from a json object

I've been reading all the stuff I can find about this, but none of the solutions seems to provide the answer I need.
Specifically, I read this Access / process (nested) objects, arrays or JSON carefully, as well as dozens of other posts.
Here's what I'm trying to accomplish:
I have a large object, called allData -- that I got as a json object from MongoDB, and it contains an array of all the data from each reading.
{pitch: -7.97, roll: -4.3, temp: 98, yaw: -129.83, time: "01/22/2016 17:28:47", …}
{pitch: -8.04, roll: -4.41, temp: 97, yaw: -130.81, time: "01/22/2016 17:28:58", …}
...
What I'd LIKE to do is be able to extract all the pitch readings with something along the lines of allData.pitch but obviously that doesn't work, since each data reading is in an element of the allData array. So I could go through in a loop and do allData[x].pitch but I was hoping for cleaner, faster way to do do this -- since I'll probably want to extract each type of data.
Unfortunately at this point I don't have the ability to simply request the pitch data from the db, so I get this whole set back.
One last wrinkle is that ONE of the elements of the array above is already a data object.
You can utilise Array.prototype.map() for this
var pitches = allData.map(function(d) {
return {
"pitch": d.pitch,
"time": d.time
};
});
If you can't control the data returned from the server (i.e., to only retrieve the pitch values you want), you are going to have to loop through to get them all.

How to return ordered key/value pairs from function?

I have an object ( array of hashes ) and I need to convert it into ordered key value pairs.
This is object:
var places_info = [
{"place_id":180,"name":"Abc","city":"Gotham"},
{"place_id":161,"name":"Def","city":"Sin City"},
{"place_id":178,"name":"Ghi","city":"Timbuktu"},
{"place_id":179,"name":"Jkl","city":"Acapulco"},
{"place_id":174,"name":"Mno","city":"Desire"}
];
And I need function to return key/value (place_id/name) pairs in same (alphabetical by name) order:
{
'180': 'Abc',
'161': 'Def',
'178': 'Ghi',
'179': 'Jkl',
'174': 'Mno'
}
Actual use: I need it as input for Jeditable Select-input (actual example on demo page). Select-type needs for data-property key/value pairs or function which returns them. So far I got select options in random order, but--as you may imagine--I need them ordered by value....
As for Jeditable the data may be just a fake hash (string formed as JSON key/value pairs), my only solution is like this:
var arr = new Array;
for ( i in places_info ) {
arr.push( "'" + places_info[i].place_id + "':'" + places_info[i].name + "'" );
}
var uglyString = '{' + arr.join(',') + '}';
Is there some more elegant and intuitive approach for such goal? I'd like to keep my data in proper data structure. Converting it to flat string seems like hack.
Edit
I must reconsider the problem. I did not test Jeditable with generated string and seems it evals string into hash and then my desired order is gone. So, this problem needs different approach. Maybe I need make my own datatype for Jeditable. But this seems like different question.
Until ES6, there is NO guaranteed order for properties on a Javascript object. They are unordered. If you need order and need to support environments before ES6, then you can't just use properties on an object and get a guaranteed order of those properties.
So your choice is to pick some other data structure that can reliably express order. Collapsing it all down to a string like you've done is one choice, though that means it has to be re-parsed in order to be useful to Javascript. It would be better to keep it in some natively accessible Javascript format. For order, that means using an array.
You can return ordered pairs by returning an array for the ordering and then there are several choices for what to put in the array. Here are several examples of ordered key/value pairs:
// array of objects
var a = [{key: "greeting", value: "hello"}, {key: "salutation", value: "welcome"}];
Since that seems a little verbose to me, I often use a shortcut that just knows that every other element is a key, then value, then key, then value and doesn't have to spell out those property names over and over:
// alternating key/value
var a = ["greeting", "hello", "salutation", "welcome"];
Or, you could put each ordered pair in an array itself so each sub-array is an ordered pair:
// sub-arrays
var a = [["greeting", "hello"], ["salutation", "welcome"]];
The properties order in objects are not guaranted in JavaScript, you need to use an Array.
Take a look at this:
var obj = {
'180': 'Abc',
'161': 'Def',
'178': 'Ghi',
'179': 'Jkl',
'174': 'Mno'
};
for (var i in obj) { console.log(i); };
will give you:
161, 174, 178, 179, 180
Just use JavaScript's native Map data structure. It preserves order. We are now way past 2015 so it should be standard in almost any runtime.
e.g.
const m = new Map([["greeting", "hello"], ["salutation", "welcome"]])
See Also https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

What String format is acceptable to append to this JSON output?

I have an existing "blackbox" web service. I need to append a session ID to the end of that output so that Javascript and similar clients can resume the stateful session.
Given the output below, what is the correct syntax to append or prepend an arbitrary GUID, so that it can be properly deserialized as valid JSON?
Note This data below is perfect. If I can somehow add a "removable" bit of information, using JSON.NET the string GUID, that would be ideal.
Output from REST call
"{\"sa\":[\"BHDQ9TLPeaeVuSSgXv9bsOIVFUWbOpivMKhGki7YPLzIXEyHuxRAZhDgts2sEcBQpLBuKJZCtcmSlzWZ9iK0AAA=\",\"BAhyo7T0Wq1WBLXnyN4vo1L94rWLhCCv4DqROi+p9XHO6UeS0Gw6xh1JAKOtXBU2fA432LkNqng8cUt1eAX0bqs=\",\"BGFmyTreWY5pICAcf3itoqbfhs5brOmIDLNF3V7p7slPYdCSVhwWUT5mHD6Lb5kNi\/Qy9tracNUtVgvo3f51FrI=\",\"BMV7RIwoz+LdFgD2fq7UZ7E88KFq\/03381NDYFIKYgUKxEzuXoj6hZfSB0slX5fdaL44Lf6i\/UjDzPQt2XUG8NE=\",\"BL8BnU5WvFn7vIlKi14dWsqykNf1\/nmE55YXFGwLx9Qu3VvDblULt\/U8CXPI1vD8+wMXCRnkunXqxlsFqgghf8w=\"],\"sb\":[\"BInTtgTAn\/zkmrkporhV5DvPZRq5YWm8e\/m02oq55UfY3RxIhOplJgwLjgKMHKYDthYEBcqNNNuVbbWnbtKVAqA=\",\"BJbh5y95wHGjmAPDFNqgewnBxtqVke0sloDD2S3IdrWZ95JfP77rtXZ4lTG8g9PuTLJbl4exZUnM16260WxJ9wU=\",\"BKevE9i2J8CicXHX3elCoQPEpTOmJyGOlBskIbFMFGQFhJ5TD7N1221rhhH9HY6DsfRojmefozsQYzo7Pokp+Hg=\",\"BJbVTRyh8WwCxfR7jRXnran4td7k5+vEfM+HWxeAibneSjdMRQ1Fg6QxKLu+Zu1aPdXqD8M29kABOTAiYopVuQE=\",\"BFv3alDqjo7ckdB2vuxJ15Gur1xsgATjLe9drt\/XU9AkbN+AELCv+mF1Xy8+83L2A1p8aGxF4b7dsrMed27u1j4=\"],\"sz\":\"BF1IiqMz0KmT4gZN6euJquWFt2UmVjyOEdaX0jH8uQMAPG8DBoyneT2PJ9NQTE2xBOP9TtAb1d2O+iCojFqzkvI=\"}"
The output above comes from Chrome. I'm not sure if Chrome adds additional quotes, etc but when I debug System.String on the server, I see the same thing being sent to the WCF service.
The end-usage for this will be a Chrome and Firefox plug in
Well if I am correctly understanding:
You get JSON from a blackbox service. It contains some properties and values. You want to add a new property with some GUID and send it to browser.
If this is correct, try following:
var json=<WHAT YOU GET FROM SERVICE>;
var converter = new ExpandoObjectConverter();
dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(json, converter);
obj.sid="this is the new session id"; //ADD NEW PROPERTY
var j=JsonConvert.SerializeObject(obj); //GET BACK JSON STRING WITH NEW PROPERTY
Of if you just want to add session id on client side (inside your plugin) the utilize JSON2 javascript library and use following code (as also suggested by Josh in comments):
var o = JSON.parse(<REST OUTPUT>);
o.sid = <YOUR SESSION ID>;
To convert back to JSON string.
var jsn = JSON.stringify(o);
There is no way to modify that particular response without breaking existing clients. If you can break existing clients, or if you are working with clients that you control, you could wrap the object in another object, setting two keys: GUID and data. For example:
var json = JsonConvert.SerializeObject(new {
data = foo,
GUID = bar,
});
Where bar is the GUID that you want to use, and foo is one of two things:
The JSON string from the response. This will result in the final object looking like so:
{
data: "{\"sa\":[\"BHDQ9TLPeaeVuSSgXv9bsOIVFUWbOpivMKhGki7YPLzIXEyHuxRAZhDgts2sEcBQpLBuKJZCtcmSlzWZ9iK0AAA=\",\"BAhyo7T0Wq1WBLXnyN4vo1L94rWLhCCv4DqROi+p9XHO6UeS0Gw6xh1JAKOtXBU2fA432LkNqng8cUt1eAX0bqs=\",\"BGFmyTreWY5pICAcf3itoqbfhs5brOmIDLNF3V7p7slPYdCSVhwWUT5mHD6Lb5kNi\/Qy9tracNUtVgvo3f51FrI=\",\"BMV7RIwoz+LdFgD2fq7UZ7E88KFq\/03381NDYFIKYgUKxEzuXoj6hZfSB0slX5fdaL44Lf6i\/UjDzPQt2XUG8NE=\",\"BL8BnU5WvFn7vIlKi14dWsqykNf1\/nmE55YXFGwLx9Qu3VvDblULt\/U8CXPI1vD8+wMXCRnkunXqxlsFqgghf8w=\"],\"sb\":[\"BInTtgTAn\/zkmrkporhV5DvPZRq5YWm8e\/m02oq55UfY3RxIhOplJgwLjgKMHKYDthYEBcqNNNuVbbWnbtKVAqA=\",\"BJbh5y95wHGjmAPDFNqgewnBxtqVke0sloDD2S3IdrWZ95JfP77rtXZ4lTG8g9PuTLJbl4exZUnM16260WxJ9wU=\",\"BKevE9i2J8CicXHX3elCoQPEpTOmJyGOlBskIbFMFGQFhJ5TD7N1221rhhH9HY6DsfRojmefozsQYzo7Pokp+Hg=\",\"BJbVTRyh8WwCxfR7jRXnran4td7k5+vEfM+HWxeAibneSjdMRQ1Fg6QxKLu+Zu1aPdXqD8M29kABOTAiYopVuQE=\",\"BFv3alDqjo7ckdB2vuxJ15Gur1xsgATjLe9drt\/XU9AkbN+AELCv+mF1Xy8+83L2A1p8aGxF4b7dsrMed27u1j4=\"],\"sz\":\"BF1IiqMz0KmT4gZN6euJquWFt2UmVjyOEdaX0jH8uQMAPG8DBoyneT2PJ9NQTE2xBOP9TtAb1d2O+iCojFqzkvI=\"}",
guid: "00000000-0000-0000-0000-000000000000"
}
And you would get at the data through two calls to JSON.parse (or the equivalent).
The deserialized object from the JSON response. This will result in the final object looking like so (most data removed for brevity sake):
{
data: {
sa: [],
sb: [],
sz: ""
},
guid: "00000000-0000-0000-0000-000000000000"
}
And you would access data through response.data.
Why any modification can break existing clients
Where the current response is an object, there are only a few ways to modify it:
Injecting a key into the object. This assumes that no client uses Object.keys() or in any way iterates the key set (e.g. for (k in obj)). While this may be true, this is an assumption.
Adding another object to the end: }, {. Doing so would require that the response be transformed into an array:
[{}, {}]
This would break any client that is assumes the response is an object.
Wrapping the current response in a surrounding object (as proposed above). This as well breaks any clients that assumes a certain structure for the response.
{data:{}, guid: ""}

Does JavaScript populate empty array items?

I am coding a lot of annual data in JavaScript, and I was considering adding it to arrays, using the year as the array index and putting the data into the array. However, Firebug seems to be indicating that JavaScript handles this by populating two thousand odd entries in the array with "undefined." With hundreds of such arrays kicking around in active memory, I'm worried the overhead of hundreds of thousands of useless array items could start to slow the program down. Will it?
When you set the value of a numeric index higher than the current length of your array, the length property is affected.
In brief, you should use an Object:
var data = {};
data[year] = "some data";
// or
var data = {
2009: "2009 data",
2010: "2010 data"
};
Now I answer the question title: "Does JavaScript populate empty array items?"
No, as I said before, only the length property is changed, (if necessary, only if the index added is larger than the current length), length is incremented to be one more than the numeric value of that index.
The Array.prototype methods work assuming that the array object will have its indexes starting from zero.
The previous indexes don't really exist in the Array object, you can test it:
var array = [];
array[10] = undefined;
array.hasOwnProperty(10); // true
array.hasOwnProperty(9); // false
In conclusion, arrays are meant to contain sequential indexes, starting from zero, if your properties don't meet those requirements, you should simply use an object.
Yes, most likely. You should consider using a JavaScript object instead:
var years = {2009: 'Good', 2010: 'Better'};
Well, if you iterate over many thousands of undefined, it will affect overall program speed, not sure if you'll notice it though.
On the other hand, sometimes a sparse array is simpler to use than a custom object,
and arrays have such handy methods available.
In a calendar application I begin with objects for each year in use, but each year consists of a twelve member (months array) and each 'month' is a sparse array of significant dates, whose lengths depend on the highest date of that month that has any data.

Categories