根据属性值对对象字面量进行排序

Sort an object literal on its attribute value

以下是我的输入,我将遍历每个元素并将每个元素发送到另一个函数。

 distinctParameterList  =  [{
        careerGroupLevel: 'Analyst',
        careerGroupCode: 130,
        m06: 83,
        m05: 82,
        m08: 85,
        fymcl: 'FY18|PromotionsOut|AN-10000100:CL 2',
        m07: 84,
        m09: 86,
        intersectionId: '54697113|India|520|N'
    },
     {
        careerGroupLevel: 'Analyst',
        careerGroupCode: 130,
        m06: 95,
        m05: 94,
        m08: 97,
        fymcl: 'FY18|PromotionsOut|AN-10000110:CL 2',
        m07: 96,
        m09: 98,
        intersectionId: '54697113|India|520|N'
    },
     {
        careerGroupLevel: 'Analyst',
        careerGroupCode: 130,
        m06: 22,
        m05: 21,
        m08: 24,
        fymcl: 'FY17|PromotionsOut|AN-10000100:CL 2',
        m07: 23,
        m09: 25,
        intersectionId: '54697113|India|520|N'
    },
     {
        careerGroupLevel: 'Analyst',
        careerGroupCode: 130,
        m06: 42,
        m05: 41,
        m08: 44,
        fymcl: 'FY17|PromotionsOut|AN-10000110:CL 4',
        m07: 43,
        m09: 45,
        intersectionId: '54697113|India|520|N'
    }]

我也在计算下面的值 "calcCareerId " :

let calcCareerId = fymclData.split("-")[1].split(":")[0];

现在我想根据 fymcl 属性中的 "calcCareerId " 值对这个结构进行排序,这样我就可以先得到所有的“10000100”值,然后再得到“10000110”值。

定义函数:

let calcCareerId = fymclData => fymclData.split("-")[1].split(":")[0];

您可以使用lodash's sortBy函数按字典顺序升序排序。如果您想要降序,只需对结果调用 .reverse 即可。

const result = _.sortBy(distinctParameterList, ({fymcl}) => calcCareerId(fymcl));

或使用原生sort:

const result = distinctParameterList.sort((a, b) => {
  const valueA = calcCareerId(a.fymcl);
  const valueB = calcCareerId(b.fymcl);
  return (valueA === valueB) ? 0 : (valueA < valueB ? 1 : -1)
})

注意原生sort会变异数组,不稳定