gpt4 book ai didi

javascript - 如何用另一个对象的键更改对象的键

转载 作者:行者123 更新时间:2023-12-01 01:20:38 25 4
gpt4 key购买 nike

我被困在将对象结果的键更改为另一个对象的另一个键,也许我的代码不是动态的,我确实喜欢从这里的人们那里得到一些提示:

function country(arr) {
var obj = {},
temp = {}
for (i of arr) {
if (i.length === 2) {
if (!temp[i[0]])
temp[i[0]] = []
temp[i[0]].push(i[1])
}

if (i.length === 3) {
obj[i[2]] = []
}

}
console.log(obj) // final result
console.log(temp)

}

var cities = [
["c", "br", "Brazil"],
["br", "Rio de Jeneiro"],
["c", "usa", "United States"],
["ru", "St. Petersburg"],
["usa", "New York"],
["ksa", "Mekkah"],
["usa", "Washington DC"],
["usa", "California"],
["c", "ch", "China"],
["ksa", "Madinah"],
["ch", "Beijing"],
["c", "ind", "India"],
["ch", "Shanghai"],
["ind", "Bangalore"],
["ind", "New Delhi"],
["c", "ru", "Rusia"],
["ru", "Moscow"],
["c", "ksa", "Arab Saudi"]
]

console.log(country(cities))

变量obj是我想要输出的键,

所以我想要的输出是这样的:

{
Brazil: [ 'Rio de Jeneiro' ],
'United States': [ 'New York', 'Washington DC', 'California' ],
............ rest...
}

是否可以将 temp 对象的键 obj 更改为变量 obj 中的键??

最佳答案

下面使用一些数组方法,即 filtermapforEach,根据请求格式化数据。

var cities = [
["c", "br", "Brazil"],
["br", "Rio de Jeneiro"],
["c", "usa", "United States"],
["ru", "St. Petersburg"],
["usa", "New York"],
["ksa", "Mekkah"],
["usa", "Washington DC"],
["usa", "California"],
["c", "ch", "China"],
["ksa", "Madinah"],
["ch", "Beijing"],
["c", "ind", "India"],
["ch", "Shanghai"],
["ind", "Bangalore"],
["ind", "New Delhi"],
["c", "ru", "Rusia"],
["ru", "Moscow"],
["c", "ksa", "Arab Saudi"]
]

let lookup = {};

cities.filter(city => city[0] === "c").forEach(country => {
let matches = cities
.filter(city => city[0] === country[1])
.map(city => city[1]);
lookup[country[2]] = matches;
});

console.log(lookup);

编辑:这是一个不使用数组函数的解决方案。

var cities = [
["c", "br", "Brazil"],
["br", "Rio de Jeneiro"],
["c", "usa", "United States"],
["ru", "St. Petersburg"],
["usa", "New York"],
["ksa", "Mekkah"],
["usa", "Washington DC"],
["usa", "California"],
["c", "ch", "China"],
["ksa", "Madinah"],
["ch", "Beijing"],
["c", "ind", "India"],
["ch", "Shanghai"],
["ind", "Bangalore"],
["ind", "New Delhi"],
["c", "ru", "Rusia"],
["ru", "Moscow"],
["c", "ksa", "Arab Saudi"]
];

let lookup = {};

for (let i = 0; i < cities.length; i++) {
// Test if this is a country
if (cities[i][0] === "c") {
// Make sure we have not processed this country before
if (!lookup[cities[i][2]]) {
lookup[cities[i][2]] = [];

let countryCode = cities[i][1];
// Loop through cities again and match country code
for (let j = 0; j < cities.length; j++) {
if (cities[j][0] === countryCode) {
lookup[cities[i][2]].push(cities[j][1]);
}
}
}
}
}

console.log(lookup);

关于javascript - 如何用另一个对象的键更改对象的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54256588/

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