Home > front end >  What is the most efficient way to display and rename only the keys from a nested JSON?
What is the most efficient way to display and rename only the keys from a nested JSON?

Time:08-20

I have the following JSON structure:

enter image description here

I will like to display only the yellow highlighted keys, rename them and then put them in a new array.

Renamed is the name of the keys:

act = Actual

prognosis = Prog

Can you please give me an example of how I can implement my plan most efficiently? plan = Planning

CodePudding user response:

I'm not quite sure I understood what you actually want, but if the structure is the same you could do something like

let result: string[] = [];

const nameMap = {
  act: 'Actual',
  plan: 'Planning',
  prognosis: 'Prog'
};

Object.keys(actAndPlanBalance).forEach(x => {
  if (actAndPlanBalance[x]['act']) result.push(nameMap.act);
  else if(actAndPlanBalance[x]['plan']) result.push(nameMap.plan);
  else if(actAndPlanBalance[x]['prognosis']) result.push(nameMap.prognosis);
});

Playground example.

  • Related