gpt4 book ai didi

javascript - 如何在 Javascript 中从 Json 数组创建路线 Path?

转载 作者:行者123 更新时间:2023-11-27 22:52:20 25 4
gpt4 key购买 nike

我有一个由一些随机城市名称组成的数组,另一个由各个城市的源和目的地组成的json对象数组,但是各个城市的这个路线数组不是按顺序排列的。我需要按照他们访问的顺序排列,我无法做出逻辑..请帮助..

城市数组(动态大小):

var CITIES = ["PARIS","LONDON","DELHI","SINGAPORE","DUBAI"]

路由的 Json 数组(随机序列):

var CITY_ROUTE = {"ROUTE":[
{"CURRENT_CITY":"PARIS","NEXT_CITY":"LONDON","PREVIOUS_CITY":"DUBAI",},
{"CURRENT_CITY":"DELHI","NEXT_CITY":"SINGAPORE","PREVIOUS_CITY":"LONDON"},
{"CURRENT_CITY":"LONDON","NEXT_CITY":"DELHI","PREVIOUS_CITY":"PARIS"},
{"CURRENT_CITY":"SINGAPORE","NEXT_CITY":"","PREVIOUS_CITY":"DELHI"},
{"CURRENT_CITY":"DUBAI","NEXT_CITY":"PARIS","PREVIOUS_CITY":""}
]};

/Required to Rearange the Json Object in Visiting sequence where Starting City will have null PREVIOUS_CITY value and Last City will have null NEXT_CITY Value/


var CITY_ROUTE_IN_SEQUENCE = {"ROUTE":[
{"CURRENT_CITY":"DUBAI","NEXT_CITY":"PARIS","PREVIOUS_CITY":""}
{"CURRENT_CITY":"PARIS","NEXT_CITY":"LONDON","PREVIOUS_CITY":"DUBAI",},
{"CURRENT_CITY":"LONDON","NEXT_CITY":"DELHI","PREVIOUS_CITY":"PARIS"},
{"CURRENT_CITY":"DELHI","NEXT_CITY":"SINGAPORE","PREVIOUS_CITY":"LONDON"},
{"CURRENT_CITY":"SINGAPORE","NEXT_CITY":"","PREVIOUS_CITY":"DELHI"}
]};

最佳答案

var CITY_ROUTE = {
"ROUTE": [
{"CURRENT_CITY":"PARIS","NEXT_CITY":"LONDON","PREVIOUS_CITY":"DUBAI",},
{"CURRENT_CITY":"DELHI","NEXT_CITY":"SINGAPORE","PREVIOUS_CITY":"LONDON"},
{"CURRENT_CITY":"LONDON","NEXT_CITY":"DELHI","PREVIOUS_CITY":"PARIS"},
{"CURRENT_CITY":"SINGAPORE","NEXT_CITY":"","PREVIOUS_CITY":"DELHI"},
{"CURRENT_CITY":"DUBAI","NEXT_CITY":"PARIS","PREVIOUS_CITY":""}
]
};

var map = {};
var point = '';
CITY_ROUTE.ROUTE.forEach(r => {
map[r.CURRENT_CITY] = r;
if (!r.PREVIOUS_CITY) {
point = r.CURRENT_CITY;
}
});

CITY_ROUTE.ROUTE = [];
while(point) {
CITY_ROUTE.ROUTE.push(map[point]);
point = map[point].NEXT_CITY;
}
console.log(JSON.stringify(CITY_ROUTE));

关于javascript - 如何在 Javascript 中从 Json 数组创建路线 Path?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37959376/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com