gpt4 book ai didi

javascript - 尝试创建对象字典时出现语法错误

转载 作者:行者123 更新时间:2023-12-04 07:56:44 24 4
gpt4 key购买 nike

我从 API 获取一组对象,如下所示:

[
{
jobId:100,
jobName: "Java",
cities:[
{
cityId:10,
name : "chicago"
},
{
statusId:11,
name : "miami"
}]
},
{
jobId:101,
jobName: "Python",
cities:[
{
cityId:11,
name : "california"
},
{
cityId:12,
name : "texas"
}]
}
]
我想访问特定工作的城市名称,如下所示:
var jobId = 101;
var cityId = 12;
var texas = jobDict[jobId].cityDict[cityId] // output: texas
代码:
angular.forEach(response.data, function (data) {
if (jobsDict[data.jobId] == undefined) {
jobsDict[data.jobId] = [];
}
angular.forEach(data.cities, function (city) {
jobsDict[data.jobId].push({
cityDic[city.cityId]: city.name // syntax error here saying unexpected token
});
});
});
我正在尝试创建一个工作字典和一个工作字典,一个城市字典。
有人可以帮我解决问题并实现所需的输出吗?

最佳答案

您的 jobsDict是一个数组,因此使用基于 0 的索引,而不是 jobID键。
同样对于嵌套的 cities .

let jobDict = [{
jobId: 100,
jobName: "Java",
cities: [{
cityId: 10,
name: "chicago"
}, {
statusId: 11,
name: "miami"
}]
}, {
jobId: 101,
jobName: "Python",
cities: [{
cityId: 11,
name: "california"
}, {
cityId: 12,
name: "texas"
}]
}];

let jobId = 101;
let cityId = 12;
let texas =
jobDict.find(job => job.jobId === jobId)
.cities.find(city => city.cityId === cityId)
.name;

console.log(texas);

跟进您的评论,如果您真的很关心性能(除非您有 1000 个条目,否则您不应该担心),这里是您如何将原始结构转换为使用工作和城市 ID 的“字典”结构的方法作为 key :

let jobs = [{
jobId: 100,
jobName: "Java",
cities: [{
cityId: 10,
name: "chicago"
}, {
cityId: 11,
name: "miami"
}]
}, {
jobId: 101,
jobName: "Python",
cities: [{
cityId: 11,
name: "california"
}, {
cityId: 12,
name: "texas"
}]
}];

let jobsById = Object.fromEntries(jobs.map(({jobId, jobName, cities}) =>
[jobId, {jobName, cities: Object.fromEntries(cities.map(({cityId, name}) => [cityId, name]))}]));

// Equivilant using tradiational for loops.
let jobsById2 = {};
for (job of jobs) {
let cities = {};
for (city of job.cities)
cities[city.cityId] = city.name;
jobsById2[job.jobId] = {jobName: job.jobName, cities};
}

console.log(jobsById[101].cities[12]);
console.log(jobsById2[101].cities[12]);

关于javascript - 尝试创建对象字典时出现语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66663053/

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