aloebys aloebys - 1 year ago 161
Javascript Question

lodash add object data to array

I have the data like

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


when i called the function updateScore like this

const result = updateStudentScore(store, {
name: 'sanji',
scores: {
math: 22,
science: 33
}
});


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

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


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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download