我目前正在尝试对我的 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;
}
}
最佳答案
我的尝试。顶部有点多余,但在检查名称之前进行空检查是有意义的。
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)
关于javascript - 对具有多个条件的对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43122931/