简体   繁体   中英

How to get inner array values in typescript

Hi I want to create a new array from existing array.

someArray = [
  {
    "abc": "abc",
    "bbc": "bbc",
    "farcKeyValues": [
      {
        "caseCreator": "xyz",
        "caseOwner": "yyy",
        "symptomCode": "123"
      },
      {
        "caseCreator": "eyz",
        "caseOwner": "tyy",
        "symptomCode": "423"
      }
    ]
  },
  {
    "xyz": "xyz",
    "yyz": "yyz",
    "farcKeyValues": [
      {
        "caseCreator": "abc",
        "caseOwner": "aaa",
        "symptomCode": "234"
      },
      {
        "caseCreator": "ybc",
        "caseOwner": "dfa",
        "symptomCode": "834"
      }
    ]
  },
  {
    "zxc": "zxs",
    "rde": "rde",
    "farcKeyValues": [
      {
        "caseCreator": "wes",
        "caseOwner": "res",
        "symptomCode": "345"
      }
    ]
  }
];

Expected array to be created is

finalValue = [
  {
    "caseCreator": "xyz",
    "caseOwner": "yyy",
    "symptomCode": "123"
  },
  {
    "caseCreator": "eyz",
    "caseOwner": "tyy",
    "symptomCode": "423"
  },
  {
    "caseCreator": "abc",
    "caseOwner": "aaa",
    "symptomCode": "234"
  },
  {
    "caseCreator": "ybc",
    "caseOwner": "dfa",
    "symptomCode": "834"
  },
  {
    "caseCreator": "wes",
    "caseOwner": "res",
    "symptomCode": "345"
  }
];

I am able to read only the first item in the farcKeyValues like below

for (var i = 0; i < this.someArray.length; i++) {
  finalValue[i] = this.someArray[i].farcKeyValues[0];
}

Any help on how to read all the elements in the inner array and create new array with all the elements?

var finalValue = [];

for (var i = 0; i < this.someArray.length; i++) {
  finalValue = [ ...finalValue, ...this.someArray[i].farcKeyValues ]
}

If you prefer a more functional approach:

var finalValue = this.someArray.reduce((acc, item) => [...acc, ...item.farcKeyValues], [])

You can read more about the spread operator here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM