如何在打字稿中迭代包含多个子数组的数组

时间:2019-10-10 07:51:27

标签: javascript typescript angular7

对不起,我在stackoverflow中遇到了类似的问题,并实现了一些问题,但没有得到确切的输出结果。
我对angular 7和打字稿都不熟悉。

我有一个数组,可能包含多个数组。该数组在运行时出现,因此我不知道单个父数组中将有多少个子数组。

例如说我有一个数组:

uniqueValues[]= [[MODERN TRADE,3959], [TRADITIONAL TRADE,2303], [ALL OTHER,1183]]

我想要这样的输出:
现代贸易
3959
传统贸易
2303
所有其他
1183

我做了什么:

getUniqueValues(name){
    this.temps.columns.forEach(element => {
      if(element.name.toUpperCase() === name.toUpperCase()){

        // it is successfully populating as you can see i have displayed it in console
        this.uniqueValues= element.stats.frequencyDistribution;

        // so the above array looks like the array defined in the starting of this post
        console.log(this.uniqueValues);
      }
      });

      for(let i = 0; i < this.uniqueValues.length; i++){
        let childArray = this.uniqueValues[i];

        for(let j = 0; j < childArray.length; j++){
          console.log(childArray[j]);
        }
      }
  }

但是它显示如下输出:
[,
M
O
D
E
R
N

T
R
A
D
E

3
9
5
9

有人可以告诉我路径吗?

2 个答案:

答案 0 :(得分:0)

对于ES6和更具可读性的功能解决方案:

const myData = [['MODERN TRADE',3959], ['TRADITIONAL TRADE',2303], ['ALL OTHER',1183]];

const processedData = myData.reduce((output, curr) => {
  const [name, value] = curr;
  output += `${name}\n${value}\n`;
  return output;
}, '');

并且因为tsc 3.6.3实际上没有推断出元组类型,所以它是一个模棱两可的类型,公平地说[string, number],而是分配了数组类型并集(string | number)[],您可以显式键入您的数据标识符为:

const myData: Array<[string, number]> = [['MODERN TRADE',3959], ['TRADITIONAL TRADE',2303], ['ALL OTHER',1183]];

请注意,每个子元素在TypeScript中都是Tuple类型。

答案 1 :(得分:-1)

使用forEach-

uniqueValues.forEach(function (child) {
  child.forEach(function (childChild) {  
    console.log(childChild);
  });  
});