Javascript 在NgRx应用程序中对对象使用Array.reduce函数
在NgRx Angular 5项目中,有一个reduce函数的用法,我不太理解。我会很感激你的帮助 基本上,代码迭代对象数组,数组如下所示:Javascript 在NgRx应用程序中对对象使用Array.reduce函数,javascript,angular,ngrx,reducers,ngrx-entity,Javascript,Angular,Ngrx,Reducers,Ngrx Entity,在NgRx Angular 5项目中,有一个reduce函数的用法,我不太理解。我会很感激你的帮助 基本上,代码迭代对象数组,数组如下所示: [{ id: '0', message: 'work', done: false }, { id: '1', message: 'movie', done: false }, { id: '2', message: 'Play', done: false }] export interfac
[{
id: '0',
message: 'work',
done: false
},
{
id: '1',
message: 'movie',
done: false
},
{
id: '2',
message: 'Play',
done: false
}]
export interface TodoState {
datas: {
[todoId: string]: Todo
}
loading: boolean;
loaded: boolean;
error: any;
}
在我的NgRx reducer中,有以下代码块:
case todosAction.FETCH_TODO_SUCCESS: {
return {
...state,
//action.payload contains above array of objects
datas: action.payload.reduce((accumulateur, iteration) => {
accumulateur[iteration.id] = iteration;
return accumulateur;
}, { ...state.datas }),
loading: false,
loaded: true,
error: null
};
}
我使用的状态如下所示:
[{
id: '0',
message: 'work',
done: false
},
{
id: '1',
message: 'movie',
done: false
},
{
id: '2',
message: 'Play',
done: false
}]
export interface TodoState {
datas: {
[todoId: string]: Todo
}
loading: boolean;
loaded: boolean;
error: any;
}
我们在这里使用reduce函数将原始源(对象数组)转换为实体(键是与todo
对象关联的id)。
我理解我们使用此函数的原因,但不理解其内部代码:
action.payload.reduce((accumulateur, iteration) => {
accumulateur[iteration.id] = iteration; // <-- AS FAR AS I UNDERSTAND, ACCUMULATOR IS NOT AN ARRAY, HOW CAN WE ACHIEVE SUCH A THING
return accumulateur;
}, { ...state.datas })
action.payload.reduce((累加器,迭代)=>{
累加器[iteration.id]=iteration;//想象一下
状态.数据
等于:
{
'0': {
id: '0',
message: 'Hello',
done: false
}
}
action.payload
等于
[{
id: '1',
message: 'World',
done: false
}]
减速器返回后,您将以
{
'0': {
id: '0',
message: 'Hello',
done: false
},
'1': {
id: '1',
message: 'World',
done: false
}
}
需要注意的重要一点是,id是一个字符串。您可以拥有一个键为'0'
的对象。这与使用任何其他字符串没有什么不同。感谢您的帮助,在reducer中,我们是否同意初始累加器值为{id:'0',message:'work',done:false}这不是一个数组,为什么我们可以使用这个:acgregateur[iteration.id]=iteration;初始值是{'0':{id:'0',message:'Hello',done:false}
。您可以在对象上设置属性值,例如:const x={}
x['0']='Hello
。它帮助了我。谢谢!