-2

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

  • can u show your attempt, and how would your "Actual" array look like? – Someone Special Aug 19 '22 at 17:02
  • My array should contain the renamed keys. That would be in the case [Actual, Actual, Actual, Actual, Actual, Prog, Planning, Planning, Planning] –  Aug 19 '22 at 17:14
  • My first approach was to iterate over the JSON with for-loop. Approach would be: for (let i in ActAndPlanBalance) { const dataInYears = ActAndPlanBalance[i]} –  Aug 19 '22 at 17:17
  • After iteration I see the individual keys with their data, but I don't know how to display and rename only the keys.... –  Aug 19 '22 at 17:20
  • Won't you lose the reference to "year" if you strip those particular properties out of their containing objects? – James Aug 19 '22 at 17:43

1 Answers1

0

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.

Gunnar B.
  • 2,879
  • 2
  • 11
  • 17
  • I tried your approach... When I call the result array via console.log after the foreach it is always empty. I think that the problem is with ['act'] and so. How do you see this? –  Aug 19 '22 at 18:16
  • 1
    Sorry, didn't correctly do the accessing. 'x' is the key, so you need to grab that object first. Fixed it. – Gunnar B. Aug 19 '22 at 18:30