aloebys
aloebys

Reputation: 123

lodash add object data to array

I have the data like

const data = [
    {}

when i called the function updateScore like this

const result = update

i want to return the new object that add the value in array

const expected = [

        ];

How can i using the lodash for add object to array data

Upvotes: 0

Views: 6035

Answers (1)

kind user
kind user

Reputation: 41893

The desired result is reachable with pure JS. Possible solution:

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));

Upvotes: 2

Related Questions