Javascript 若数组中存在对象值,则添加到现有对象
我有一个函数组件,它根据对象数组在react中生成一个线性图 我从API中提取的数据如下所示:Javascript 若数组中存在对象值,则添加到现有对象,javascript,reactjs,react-hooks,Javascript,Reactjs,React Hooks,我有一个函数组件,它根据对象数组在react中生成一个线性图 我从API中提取的数据如下所示: { "_id": "604face09b305032586fe235", "username": "Demo", "description": "0", "duration": 0,
{
"_id": "604face09b305032586fe235",
"username": "Demo",
"description": "0",
"duration": 0,
"date": "2021-03-15T18:52:10.749Z",
"createdAt": "2021-03-15T18:52:16.684Z",
"updatedAt": "2021-03-15T18:52:16.684Z",
"__v": 0
}
我生成图表数据的代码是:
// GET Exercises
useEffect(() => {
axios.get("http://localhost:5000/exercises")
.then((result) => {
setIsLoaded(true);
setItems(result.data);
console.log(result.data)
})
.catch((error) => {
setIsLoaded(true);
setError(error);
})
}, [])
// chartdata
useEffect(() => {
const chartArray = items.map((item) => {
const container = {};
container.label = item.username;
container.data = [[stripDate(item.date), item.duration]]
return container;
});
setXp(chartArray);
}, [items])
但是,API可以返回多个带有“username”的对象:“Demo”,我想要的是,如果我的图表数据中已经存在username值,我想用另一个数组更新该container.data
数组
当前成果:
{
"label": "Demo",
"data": [[15, "2021-03-15"]]
},
{
"label": "Demo",
"data": [[45, "2021-03-17"]]
}
我想要达到的目标:
{
"label": "Demo",
"data": [[15, "2021-03-15"], [45, "2021-03-17"]]
}
非常感谢您的帮助或指导。您需要使用对象累加器中的
数组#reduce
根据用户名
值对数据进行分组。对于重复的用户名
在数组中推送新的数据
。然后使用Object.values()
从该累加器获取值
useEffect(() => {
const chartArray = Object.values(items.reduce((r, o) => {
r[o.username] = r[o.username] || { label: o.username, data: []};
r[o.username].data.push([o.duration, stripDate(o.date)]);
return r;
},{}));
setXp(chartArray);
}, [items])