Home > Software design >  More efficient ways to assign properties to an interface?
More efficient ways to assign properties to an interface?

Time:07-08

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]);

CodePudding user response:

You can do this

countersData = {
  ...countersData,
  ...flattenObject(responseDeploymentData)
}

CodePudding user response:

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);
  • Related