lodash将对象数据添加到数组中

时间:2017-07-27 08:53:47

标签: javascript arrays ecmascript-6 lodash

我有像

这样的数据
const data = [
    {}

当我像这样调用函数updateScore时

const result = update

我想返回在数组中添加值的新对象

const expected = [

        ];

如何使用lodash将对象添加到数组数据

1 个答案:

答案 0 :(得分:2)

使用纯JS可以获得所需的结果。可能的解决方案:

const data = [
    {
        subject: 'math',
        students: [{ name: 'luffy', score: 10 }, { name: 'zoro', score: 15 }]
    },
    {
        subject: 'science',
        students: [{ name: 'luffy', score: 15 }, { name: 'zoro', score: 25 }]
    }
];

const obj = { 
    name: 'sanji',
    scores: {
      math: 22,
      science: 33
    }
}

const updateStudentScore = ({ name, scores }) => {
  Object.keys(scores).forEach(v => {
    data.find(c => c.subject == v).students
        .push({ name: name, score: scores[v] })
  });
  return data;
}

console.log(updateStudentScore(obj));