将数据分配给for中的对象

时间:2019-01-22 15:21:58

标签: javascript

我正在尝试将循环数据添加到对象。

subItem.allAvgObj = {};

for(var i = 0; i < subItem.implementations.length; i++) {

if (subItem.implementations[i].avg_score) {

        Object.assign(subItem.allAvgObj, {
          scoreAvg: subItem.implementations[i].avg_score,
          scorePonderation: subItem.implementations[i].ponderation,
        })

    }
}

仅,分配了我循环的最后一个对象。

{
 "scoreAvg": 8,
 "scorePonderation": 10
}

我尝试了一个数组,它可以工作(但它是一个具有单个值的数组,但是循环有效)

subItem.allAvgArray.push(subItem.implementations[i].avg_score);

返回:

[
  13.5,
  16,
  8
]

如何制作这样的物体?

{
  "scoreAvg": 13.5,
  "scorePonderation": 20
},
{
  "scoreAvg": 16,
  "scorePonderation": 20
},
{
  "scoreAvg": 8,
  "scorePonderation": 10
}

谢谢

2 个答案:

答案 0 :(得分:4)

创建对象数组的一种更简单的方法可能是使用.filter()删除没有avg_score()的对象,然后使用.map()从每个项目创建结果对象。

let result = subItem.implementations
  .filter(i => i.avg_score)
  .map(i => ({
    scoreAvg: i.avg_score,
    scorePonderation: i.ponderation
  }));

const subItem = {
  implementations: [{
      avg_score: 15.7,
      ponderation: 20
    },
    {
      avg_score: 0,
      ponderation: 15
    }, {
      avg_score: 6.8,
      ponderation: 10
    }
  ]
}

let result = subItem.implementations
  .filter(i => i.avg_score)  //remove items without avg_score
  .map(i => ({               //turn the remaining items into objects
    scoreAvg: i.avg_score,
    scorePonderation: i.ponderation
  }));
  
console.log(result);

或者,reduce()提供一种解决方案。

let result = subItem.implementations
  .reduce((acc,i) => 
    i.avg_score 
      ? [...acc, {scoreAvg: i.avg_score, scorePonderation: i.ponderation}] 
      : acc
  ,[]);

const subItem = {
  implementations: [{
      avg_score: 15.7,
      ponderation: 20
    },
    {
      avg_score: 0,
      ponderation: 15
    }, {
      avg_score: 6.8,
      ponderation: 10
    }
  ]
}

let result = subItem.implementations
  .reduce((acc,i) => 
    i.avg_score  //if avg_score, add an object. else, do nothing.
      ? [...acc, {scoreAvg: i.avg_score, scorePonderation: i.ponderation}] 
      : acc
  ,[]);

console.log(result);

请注意,reduce()解决方案在性能上弥补了它缺乏可读性的缺点。

答案 1 :(得分:2)

Object.assign用于浅合并对象,而不是创建似乎是您想要的对象的数组。

尝试:

subItem.allAvgObj = [];

for(var i = 0; i < subItem.implementations.length; i++) {

if (subItem.implementations[i].avg_score) {

        subItem.allAvgObj.push({
          scoreAvg: subItem.implementations[i].avg_score,
          scorePonderation: subItem.implementations[i].ponderation,
        })

    }
}

预期输出应为:

[
    {
      "scoreAvg": 13.5,
      "scorePonderation": 20
    },
    {
      "scoreAvg": 16,
      "scorePonderation": 20
    },
    {
      "scoreAvg": 8,
      "scorePonderation": 10
    }
]