【问题标题】:lodash add object data to arraylodash 将对象数据添加到数组
【发布时间】:2017-07-27 08:53:46
【问题描述】:

我有类似的数据

const data = [
    {}

当我这样调用函数 updateScore 时

const result = update

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

const expected = [

        ];

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

【问题讨论】:

    标签: javascript arrays ecmascript-6 lodash


    【解决方案1】:

    使用纯 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));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-20
      • 1970-01-01
      • 2016-05-31
      • 2022-01-13
      • 2018-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多