Question
· Mar 7, 2019

JSON challenge

Hello folks,

I have an JSON object that need to be updated before being parsed into a JSX component.

Source JSON obj:

var Obj = { "data": [
  {"id":1, "text":"Task #1", "project":"10", "sub_project":"10-1" },
  {"id":2, "text":"Task #2", "project":"10", "sub_project":"10-1" },
  {"id":3, "text":"Task #3", "project":"11", "sub_project":"11-1" },
]};

 

Required JSON obj result:

var Obj = { "data": [

  {"id":10, "text":"Project 10" },
  {"id":11, "text":"Project 11" },

  {"id":10-1, "text":"Sub Project 10-1", "project":"10" },
  {"id":11-1, "text":"Sub Project 11-1", "project":"11" },

  {"id":1, "text":"Task #1", "project":"10", "sub_project":"10-1" },
  {"id":2, "text":"Task #2", "project":"10", "sub_project":"10-1" },
  {"id":3, "text":"Task #3", "project":"11", "sub_project":"11-1" },

 

What's the best way to update this JSON object "data" to return the required result. The JSON source has only tasks items, but need to include/append all projects and sub-projects (unique values).

Discussion (1)0
Log in or sign up to continue

I' do it in 2 steps.

  1. Iterate over data array and build a temp local structure to hold all additional items you need
  2. Iterate over this new structure and add these items to data array.

You can add to array using %Push method:

do Obj.data.%Push(newItem)

If you want to push at a specific posiiton, use %Set

do Obj.data.%Set(position, newItem)

That said your later structure contains data which does not exist in the original structure (text values for projects and sub-projects) so you need to get it from somewhere.

Also is project - subproject hierarchy one-level, or there could be an arbitrary number of sub-project levels (i.e. 10  10-1 → 10-1-1 → 10-1-1-1)?