根据两个字段对json进行排序

时间:2020-07-31 07:15:13

标签: javascript html json

我有一个json响应,我想根据两个字段对数据进行排序Geo字段需要按字母顺序排列,salesStage字段按已确定,合格,已关闭的获胜订单进行排序

const summary_data = [
{Geo:"US West",SalesStage:"Closed Won",count:2,pipelinevalue:356},
{Geo:"US East",SalesStage:"Closed Won",count:8,pipelinevalue:35},
{Geo:"US West",SalesStage:"Qualified",count:16,pipelinevalue:6},
{Geo:"US East",SalesStage:"Qualified",count:3,pipelinevalue:3},
{Geo:"US East",SalesStage:"Identified",count:50,pipelinevalue:6},
{Geo:"US West",SalesStage:"Identified",count:39,pipelinevalue:3},
{Geo:"NSU",SalesStage:"Identified",count:20,pipelinevalue:8}];
data=summary_data.sort((a, b) => a.Geo.localeCompare(b.Geo));
console.log(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

预期为

[
{Geo:"NSU",SalesStage:"Identified",count:20,pipelinevalue:8},
{Geo:"US East",SalesStage:"Identified",count:50,pipelinevalue:6},
{Geo:"US East",SalesStage:"Qualified",count:3,pipelinevalue:3},
{Geo:"US East",SalesStage:"Closed Won",count:8,pipelinevalue:35},
{Geo:"US West",SalesStage:"Identified",count:39,pipelinevalue:3},
{Geo:"US West",SalesStage:"Qualified",count:16,pipelinevalue:6},
{Geo:"US West",SalesStage:"Closed Won",count:2,pipelinevalue:356}
];

2 个答案:

答案 0 :(得分:3)

您需要为SalesStage添加排序。这适用于阶段的对象和顺序值。

const
    summary_data = [{ Geo: "US West", SalesStage: "Closed Won", count: 2, pipelinevalue: 356 }, { Geo: "US East", SalesStage: "Closed Won", count: 8, pipelinevalue: 35 }, { Geo: "US West", SalesStage: "Qualified", count: 16, pipelinevalue: 6 }, { Geo: "US East", SalesStage: "Qualified", count: 3, pipelinevalue: 3 }, { Geo: "US East", SalesStage: "Identified", count: 50, pipelinevalue: 6 }, { Geo: "US West", SalesStage: "Identified", count: 39, pipelinevalue: 3 }, { Geo: "NSU", SalesStage: "Identified", count: 20, pipelinevalue: 8 }],
    order = { Identified: 1, Qualified: 2, 'Closed Won': 3 };

summary_data.sort((a, b) =>
    a.Geo.localeCompare(b.Geo) ||
    order[a.SalesStage] - order[b.SalesStage]
);

console.log(summary_data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:1)

尝试使用Array.sort()。在回调中,按char strings[10][100], ** ptr = strings; 进行排序,但是如果要比较的对象中它们相同,则按Geo进行排序。返回SalesStageGeo的比较值,具体取决于哪个值。