如何根据打字稿中的键从对象中提取特定元素

How to extract a particular element from an object based on key in typescript

我有一个要求,需要根据特定键从 JSON 对象中提取 element/attribute。我在这里非常困惑如何获取。

{   "metadata":{
      "lastSyncTime":"2000-11-21T16:07:53",
      "dataFromDB":true
   },
   "allocationReports":[      {
         "allocatedUserCount":100,
         "healthGoalName":"Eat Healthier",
         "segments": [
            {segmentValue: "40-49", allocatedUserCount: 2}, 
            {segmentValue: "30-39", allocatedUserCount: 13},
            {segmentValue: "20-29", allocatedUserCount: 23}
         ]
      },
      {
         "allocatedUserCount":130,
         "healthGoalName":"Feel Happier",
         "segments": [
            {segmentValue: "40-49", allocatedUserCount: 20}, 
            {segmentValue: "30-39", allocatedUserCount: 3},
            {segmentValue: "20-29", allocatedUserCount: 53}
         ]
      },
  
      {
         "allocatedUserCount":150,
         "healthGoalName":"Quit Smoking",
         "segments": [
            {segmentValue: "40-49", allocatedUserCount: 19}, 
            {segmentValue: "30-39", allocatedUserCount: 1},
            {segmentValue: "20-29", allocatedUserCount: 22},
            {segmentValue: "10-19", allocatedUserCount: 47}
         ]
      }
   ],
   "overall":{
      "usersWithGoalCount":0,
      "registeredCount":500,
      "eligibleCount":280
   }
}

我们如何根据 healthgoalName 提取段数组。例如,我写了一个以 'healthGoalName'(比方说戒烟)为参数的方法。 这个方法应该return -

"segments": [
   {segmentValue: "40-49", allocatedUserCount: 19}, 
   {segmentValue: "30-39", allocatedUserCount: 1},
   {segmentValue: "20-29", allocatedUserCount: 22},
   {segmentValue: "10-19", allocatedUserCount: 47}
]

提前致谢。

我假设问题中的 JSON 显示了名为 obj 的对象的内容,该对象在名为 getSegments 的方法的上下文中可用。如果不是这种情况,您需要将该对象作为第二个参数提供给该方法。

function getSegments(healthGoalName)
{
    const allocationReport = obj.allocationReports.find(allocationReport => allocationReport.healthGoalName === healthGoalName);
    return allocationReport ? allocationReport.segments : null;
}

function getSegments(healthGoalName)
{
    const allocationReport = obj.allocationReports.find(allocationReport => allocationReport.healthGoalName === healthGoalName);
    return allocationReport ? allocationReport.segments : null;
}

const obj =
{
    "metadata":{
      "lastSyncTime":"2000-11-21T16:07:53",
      "dataFromDB":true
   },
   "allocationReports":[      {
         "allocatedUserCount":100,
         "healthGoalName":"Eat Healthier",
         "segments": [
            {segmentValue: "40-49", allocatedUserCount: 2}, 
            {segmentValue: "30-39", allocatedUserCount: 13},
            {segmentValue: "20-29", allocatedUserCount: 23}
         ]
      },
      {
         "allocatedUserCount":130,
         "healthGoalName":"Feel Happier",
         "segments": [
            {segmentValue: "40-49", allocatedUserCount: 20}, 
            {segmentValue: "30-39", allocatedUserCount: 3},
            {segmentValue: "20-29", allocatedUserCount: 53}
         ]
      },
  
      {
         "allocatedUserCount":150,
         "healthGoalName":"Quit Smoking",
         "segments": [
            {segmentValue: "40-49", allocatedUserCount: 19}, 
            {segmentValue: "30-39", allocatedUserCount: 1},
            {segmentValue: "20-29", allocatedUserCount: 22},
            {segmentValue: "10-19", allocatedUserCount: 47}
         ]
      }
   ],
   "overall":{
      "usersWithGoalCount":0,
      "registeredCount":500,
      "eligibleCount":280
   }
};

const segments = getSegments("Quit Smoking");
console.log({ segments });

最好先键入数据的结构,例如:

interface Segment {
  segmentValue: string;
  allocatedUserCount: number;
}

interface AllocationReport {
  allocatedUserCount: number;
  healthGoalName: string;
  segments: Segment[];
}

interface Data {
  metadata: {
    lastSyncTime: string;
    dataFromDB: boolean;
  }
  allocationReports: AllocationReport[];
}

然后,您可以编写一个函数来获取 segments,如下所示:

const search = (data: Data, healthGoalName: string): Segment[] | undefined => {
  for (const allocationReport of data.allocationReports) {
    if (allocationReport.healthGoalName === healthGoalName) {
      return allocationReport.segments;
    }
  }

  return undefined;
};

查看片段中的注释

const dataObject = {"metadata":{
    "lastSyncTime":"2000-11-21T16:07:53",
    "dataFromDB":true
 },
 "allocationReports":[      {
       "allocatedUserCount":100,
       "healthGoalName":"Eat Healthier",
       "segments": [
          {segmentValue: "40-49", allocatedUserCount: 2}, 
          {segmentValue: "30-39", allocatedUserCount: 13},
          {segmentValue: "20-29", allocatedUserCount: 23}
       ]
    },
    {
       "allocatedUserCount":130,
       "healthGoalName":"Feel Happier",
       "segments": [
          {segmentValue: "40-49", allocatedUserCount: 20}, 
          {segmentValue: "30-39", allocatedUserCount: 3},
          {segmentValue: "20-29", allocatedUserCount: 53}
       ]
    },

    {
       "allocatedUserCount":150,
       "healthGoalName":"Quit Smoking",
       "segments": [
          {segmentValue: "40-49", allocatedUserCount: 19}, 
          {segmentValue: "30-39", allocatedUserCount: 1},
          {segmentValue: "20-29", allocatedUserCount: 22},
          {segmentValue: "10-19", allocatedUserCount: 47}
       ]
    }
 ],
 "overall":{
    "usersWithGoalCount":0,
    "registeredCount":500,
    "eligibleCount":280
 }
}

function findSegments(data,query) {
    //if data layer is an object
    if(!Array.isArray(data)){
        return Object.entries(data).reduce((output,[key,val]) => {
          //and if property is an array
          if(Array.isArray(val)){
              //run recursion 
              output = findSegments(val, query);
              return output; 
          }
          //otherwise ignore
          return output;
        },{})
    //if data layer is an array
    } else {
        return data.reduce((output,ele)=> {
            //and if healthGoalName matches query ignore
            if(ele.healthGoalName === query) {
                //extract segments
               output.segments = ele.segments;
               return output;       
            }
            //otherwise ignore
            return output;              
        }, {})
    } 
}
//pass original data object and healthGoalName query value
console.log(findSegments(dataObject,"Quit Smoking"))