对于数组上的循环,键入script/Javascript,将键的值作为值为1的键推送到新数组中-若已经存在,则递增

对于数组上的循环,键入script/Javascript,将键的值作为值为1的键推送到新数组中-若已经存在,则递增,javascript,arrays,json,angular,typescript,Javascript,Arrays,Json,Angular,Typescript,其目的是使一个数组包含来自另一个数组的特定键的所有唯一值。这些唯一值(现在是新数组中的键)的值为它们在原始数组中出现的次数 这是我目前的代码: for (let i = 0; i < data.length; i++) { let theStupidKey = data[i].DeliveryStatus; if ( this.differentValuesOfStatus.indexOf(theStupidKey

其目的是使一个数组包含来自另一个数组的特定键的所有唯一值。这些唯一值(现在是新数组中的键)的值为它们在原始数组中出现的次数

这是我目前的代码:

for (let i = 0; i < data.length; i++) {


           let theStupidKey = data[i].DeliveryStatus;

           if (
             this.differentValuesOfStatus.indexOf(theStupidKey) == "-1"
           ) {
             this.differentValuesOfStatus.push(theStupidKey: 1);
             // this.differentValuesOfStatus[theStupidKey].push(theStupidKey = 1);
           }
           else {
             this.differentValuesOfStatus[theStupidKey] = 1
           }
        }
        console.log(this.differentValuesOfStatus);
      };
for(设i=0;i
但是语法是错误的,我想尽一切办法让它工作

基本上我是在一个数组中循环

如果第二个数组中不存在'deliverystatus'键的值,我将使用值“1”添加它


如果它已经存在,我想给它添加另一个数字。

一个数组只能保存一个值列表。如果要存储键和相应的值,应使用映射:

class Test {
  differentValuesOfStatus: Map<string, number>;

  test(data: {DeliveryStatus: string}[]) {
    this.differentValuesOfStatus = new Map<string, number>();
    for (let i = 0; i < data.length; i++) {
      let theStupidKey = data[i].DeliveryStatus;

      let value = this.differentValuesOfStatus.get(theStupidKey);
      this.differentValuesOfStatus.set(theStupidKey,
        (value === undefined ? 0 : value) + 1);
    }
    console.log(this.differentValuesOfStatus);
  }
}

let t = new Test();
t.test([
  { DeliveryStatus: "Accepted" },
  { DeliveryStatus: "Rejected" },
  { DeliveryStatus: "Accepted" }
]);
类测试{
不同的状态:地图;
测试(数据:{DeliveryStatus:string}[]){
this.differentValuesOfStatus=新映射();
for(设i=0;i
我认为您可以创建一个对象,将您的状态名称作为键,将出现编号作为值。下面是实现这一点的代码

for (let i = 0; i < data.length; i++)
{
    let theStupidKey = data[i].DeliveryStatus;

    if (!this.differentValuesOfStatus.hasOwnProperty(theStupidKey)) {
        this.differentValuesOfStatus[theStupidKey] = 0;
    }
    this.differentValuesOfStatus[theStupidKey] = this.differentValuesOfStatus[theStupidKey] + 1;
}
console.log(this.differentValuesOfStatus);
但是如果你想要一个数组,你可以这样做

let newArray = [];
for (var key in this.differentValuesOfStatus) {
    newArray.push({ "Status": key, "Occurence": this.differentValuesOfStatus[key] });
}
console.log(newArray);
输出将是

[{status: "Status1", Occurence: 2},
{status: "Status2", Occurence: 3},
{status: "Status3", Occurence: 1},
{status: "Status4", Occurence: 3}]
[{status: "Status1", Occurence: 2},
{status: "Status2", Occurence: 3},
{status: "Status3", Occurence: 1},
{status: "Status4", Occurence: 3}]