You could simplify the use of the found object by checking if it does not exist and push a new object to the result set.
Then push an object with value
and count
to data
.
const
array = [{ name: "qewregf dqewafs", value: "qewregf dqewafs answer", count: 2 }, { name: "survey with select", value: "survey with select answer", count: 2 }, { name: "werasd", value: "Donald", count: 1 }, { name: "werasd", value: "Jim", count: 1 }],
result = array.reduce((r, { name, value, count }) => {
var temp = r.find(o => name === o.name);
if (!temp) {
r.push(temp = { name, data: [] });
}
temp.data.push({ value, count });
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }