kumar jain
kumar jain

Reputation: 99

destructuring inner objects with same name property

hi all I have below object structure that i am trying to get the name of all inner objects using destructuring technique but could not be able to do that, Below is the object structure

   {
       massingType {
            id
            name
        }
        ashraeClimateZone {
             id
            name
        }
        sourceOfData {
             id
             name    
        }
        .....
    } 

and i am doing the destrcturing like as below

 constructionSetData.constructionSets.forEach(item => {
    if (
      item.ashraeClimateZone?.id === ashraeClimateZoneId &&
      item.massingType?.id === massingTypeId &&
      item.sourceOfData?.id === energyCodeId
    ) {
      matchedConstructionDataSet.push(item.name);
      const { sourceOfData: name, massingType: name, ashraeClimateZone: name } = item; // getting error here Identifier 'name' has already been declared 
    }
  });
  return matchedConstructionDataSet.length
    ? `${matchedConstructionDataSet.join(', ')}` // here i need to use above names coming from three inner objects
    : 'No construction set found with the current criteria';

Could any one please let me know how can i achieve this solution, many thanks in advance!!

Upvotes: 2

Views: 1987

Answers (1)

Drew Reese
Drew Reese

Reputation: 202686

Using destructuring assignment you can rename any destructured variables. You are currently renaming each "root" key as name which is causing duplicate declarations, but it appears you really want to access & destructure the nested name property of each.

const {
  sourceOfData: {
    name: sourceOfDataName,
  },
  massingType: {
    name: massingTypeName,
  },
  ashraeClimateZone: {
    name: ashraeClimateZoneName,
  },
} = item;

Considering just the first destructured value, the above

  1. destructure assigns sourceOfData from item
  2. destructure assigns the name property to sourceOfDataName.

Upvotes: 6

Related Questions