Split a combined List based on particular gender data is present for ID

喜你入骨 提交于 2020-05-14 07:56:28

问题


Here is a combined list, with unique ageCode.

    [
      {
        "ageCode": 1,
        "ageDesc": "0-4",
        "qM": 358,
        "sM": 158,
        "qF": 328,
        "sF": 258
      },
      {
        "ageCode": 3,
        "ageDesc": "15-59",
        "qM": 525,
        "sM": 125
      },
      {
        "ageCode": 4,
        "ageDesc": "60+",
        "qF": 458,
        "sF": 358
      }
    ]

Combined list need to be split into individual object based on if both M & F value is present for an ageCode. The converted list look like this. If there is No "M" date then there will be no object with "gender": "M" same applied to "F"

    [
      {
        "ageCode": 1,
        "ageDesc": "0-4",
        "q": 358,
        "s": 158,
        "gender": "M"
      },
      {
        "ageCode": 1,
        "ageDesc": "0-4",
        "q": 328,
        "s": 258,
        "gender": "F"
      },
      {
        "ageCode": 3,
        "ageDesc": "15-59",
        "q": 525,
        "s": 125,
        "gender": "M"
      },
      {
        "agCode": 4,
        "ageDesc": "60+",
        "q": 458,
        "s": 358,
        "gender": "F"
      }
    ]

Solution tried:

      for(let item  of this.ageData) {
            if (this.ageData.find((i) => { i.agCode=== item.agCode})){

    //}

        }

Here issues like duplicate and multiple for loop is required, Is there any efficient way to achieve this.


回答1:


Try the next code

const combined = [
  {
    "ageCode": 1,
    "ageDesc": "0-4",
    "qM": 358,
    "sM": 158,
    "qF": 328,
    "sF": 258
  },
  {
    "ageCode": 3,
    "ageDesc": "15-59",
    "qM": 525,
    "sM": 125
  },
  {
    "ageCode": 4,
    "ageDesc": "60+",
    "qF": 458,
    "sF": 358
  }
];

const original = combined.reduce((result, item) => {
  if (item.qM !== undefined) {
    result.push({
      "ageCode": item.ageCode,
      "ageDesc": item.ageDesc,
      "q": item.qM,
      "s": item.sM,
      "gender": "M"
    });
  }
  if (item.qF !== undefined) {
    result.push({
      "ageCode": item.ageCode,
      "ageDesc": item.ageDesc,
      "q": item.qF,
      "s": item.sF,
      "gender": "F"
    });
  }
  return result;
}, []);

console.log(original);


来源:https://stackoverflow.com/questions/61710616/split-a-combined-list-based-on-particular-gender-data-is-present-for-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!