我目前正在尝试对我的reducer中返回的对象数组进行排序。我想根据正在返回的name
对应用进行排序,目前仍有一些null
名称,我想在最后列出null
名称。目前,当我尝试添加其他条件时,我收到错误Cannot read property 'toLowerCase' of null
我希望null
项只需要将它们移动到最后。
// Actions
export const FETCH_MYAPPS_PENDING = 'widgets/apps/FETCH_PENDING';
export const FETCH_MYAPPS_FULFILLED = 'widgets/apps/FETCH_FULFILLED';
// Reducer
const appsSort = (a, b) => {
if (a.name != null && b.name != null) {
if (a.name.toLowerCase() > b.name.toLowerCase()) return 1;
if (a.name.toLowerCase() < b.name.toLowerCase()) return -1;
}
return 0;
};
export default function reducer(state = { data: [], pending: false }, action) {
switch (action.type) {
case FETCH_MYAPPS_FULFILLED:
return {
data: action.apps.sort(appsSort),
pending: false,
retrievedAt: Date.now(),
};
case FETCH_MYAPPS_PENDING:
return {
...state,
pending: true,
};
default:
return state;
}
}
答案 0 :(得分:1)
我的尝试。它在顶部稍微多余,但在检查名称之前进行空检查是有意义的。
const appsSort = (a, b) => {
//null checks
if (a.name === null && b.name === null) return 0;
if (a.name === null && b.name !== null) return 1;
if (b.name === null && a.name !== null) return -1;
//check for lowercase
if (a.name.toLowerCase() > b.name.toLowerCase()) return 1;
if (a.name.toLowerCase() < b.name.toLowerCase()) return -1;
return 0;
};
var obj = [
{name: 'apples', id: 1},
{name: null, id: 3},
{name: 'Banana', id: 2},
{name: null, id: 4}
]
obj.sort(appsSort);
console.log(obj)
答案 1 :(得分:1)
您可以使用null
检查作为排序值,稍后使用localeCompare
进行排序,并使用链式方法logical OR ||
进行排序。
const appsSort = (a, b) =>
(a.name === null) - (b.name === null) ||
('' + a.name).localeCompare(b.name);
var obj = [{ name: 'apples', id: 1 }, { name: null, id: 3 }, { name: 'Banana', id: 2 }, { name: null, id: 4 }];
obj.sort(appsSort);
console.log(obj)
答案 2 :(得分:0)
该错误表明a.name
或b.name
无法解析为使用方法toLowerCase
的对象。
在尝试对它们调用toLowerCase
之前,您可以确保两者的值都是字符串。这是检查值是否为&#39;字符串&#39;
typeof a.name === 'string'