0

I assign the properties of an interface CountersData as seen below. I use a flattenObject to extract the most nested key and value data from responseDeploymentData (as detailed One liner to flatten nested object)

This is clunky, so is there a more efficient/simple way to do this? See code below:

interface CountersData {
  //more properties

  count_targets?: number;
  count_targets_excluded?: number;
  count_targets_pending?: number;
  count_targets_in_progress?: number;
  count_targets_completed?: number;
  count_targets_failed?: number;
}
// later in code
  const countersData = {} as CountersData;
  let targetData: any = flattenObject(responseDeploymentData);
  countersData.count_targets = targetData.count_targets;
  countersData.count_targets_excluded = targetData.count_targets_excluded;
  countersData.count_targets_pending = targetData.count_targets_pending;
  countersData.count_targets_in_progress = targetData.count_targets_in_progress;
  countersData.count_targets_completed = targetData.count_targets_completed;
  countersData.count_targets_failed = targetData.count_targets_failed;

Updated Fix: ['count_targets', 'count_targets_excluded'].forEach(key => countersData[key] = targetData[key]);

user19251203
  • 322
  • 4
  • 13

2 Answers2

0

You can do this

countersData = {
  ...countersData,
  ...flattenObject(responseDeploymentData)
}
  • I am getting an error `Cannot assign to 'countersData' because it is a constant.` I will update my code above to include line: `const countersData = {} as CountersData;` – user19251203 Jul 07 '22 at 18:06
  • Define countersData with "let" instead of "const" where it is initially defined. If this is not a possibility, then this won't work. – Bruno Ribarić Jul 08 '22 at 21:35
0

If flattenObject(...) returns the whole object which you need to put into counterData, then use:

const counterData = flattenObject(...);

If flattenObject(...) only returns partial data, then you might want to do a destructuring assignment:

const countersData = {} as CountersData;
const targetData: any = flattenObject(responseDeploymentData);

({
  count_targets: counterData.count_targets,
  count_targets_excluded: counterData.count_targets_excluded,
  count_targets_pending: counterData.count_targets_pending,
  count_targets_in_progress: counterData.count_targets_in_progress,
  count_targets_completed: counterData.count_targets_completed,
  count_targets_failed: counterData.count_targets_failed,
} = targetData);
funkycoder
  • 525
  • 4
  • 17