我正在寻找在JavaScript中将相关数组合并在一起的最干净,最酷的方式。
我的例子就是这样:
我从我的API获取了两个JSON数组:问题和位置。
问题有location_id
,因此我想为每个问题提供一个location
字段,该字段具有正确的location
对象,具体取决于问题{{1} }。
如果我有这些数据:
location_id
丑陋的解决方案是:
var issues = [{id: 1, title: 'issue 1', location_id: 1}, {id: 12, title: 'issue 1', location_id: 2}];
var locations = [{id: 1, name: 'location 1'}, {id: 2, name: 'location 2'}];
生成的for(i = 0; i < issues.length; ++i) {
for(j = 0; j < locations.length; ++j) {
if(issues[i].location_id == locations[j].id) {
issues[i].location = locations[j];
break;
}
}
}
数组将是:
issues
我正在尝试(并且失败)使用.map()来提出更短的解决方案甚至是一个班轮。
任何指导赞赏!! :)
答案 0 :(得分:3)
issues.map(function (issue) {
issue.location = locations.filter(function(location) {
return issue.location_id === location.id;
})[0];
return issue;
});
答案 1 :(得分:1)
使用object
保留地图,时间复杂度为O(n+m)
而不是O(n*m)
。
var issues = [{id: 1, title: 'issue 1', location_id: 1}, {id: 12, title: 'issue 1', location_id: 2}];
var locations = [{id: 1, name: 'location 1'}, {id: 2, name: 'location 2'}];
var binds = function(locationList, issueList) {
var locMap = {};
// clone. If you want to directly modify the issues, this line is no need.
issueList = JSON.parse(JSON.stringify(issueList));
// construct map from location list.
locationList.forEach(function(location) {
locMap[location.id] = location;
});
// Use the map to bind location and issue.
issueList.forEach(function(issue) {
var loc = locMap[issue.location_id];
if (loc) {
issue.location = loc;
}
});
// If you don't want to clone, this line is no need.
return issueList;
};
var bindResult = binds(locations, issues);
console.log(bindResult);
答案 2 :(得分:0)
您可以使用forEach和过滤器
var result = issues.forEach(function (issue) {
issue.location = locations.filter(function (location) {
return location.id == issue.location_id;
})[0]
})
在console.log(结果)
时为您提供此输出[{ "id": 1, "title": "issue 1", "location_id": 1, "location": { "id": 1, "name": "location 1" } }, { "id": 12, "title": "issue 1", "location_id": 2, "location": { "id": 2, "name": "location 2" } }]
答案 3 :(得分:0)
1。您可以将代码优化为:
var locationObj = {};
for(i = 0; i < location.length; i++) {
locationObj[location[i].id] = location[i];
}
for(i = 0; i < issues.length; i++) {
if(issues[i].location_id){
issues[i].location = locationObj[location_id]
}
}
它将缓存一个对象中的所有位置,并将直接使用该位置将其详细描述为该对象的属性。执行速度更快,而不是每次都在位置数组上使用过滤器或贴图。
2。如果您的位置的ID和位置数组的索引位于同步,那么以下将是一个更好,更快的解决方案。
for(i = 0; i < issues.length; i++) {
if(issues[i].location_id){
issues[i].location = locations[location_id-1]
}
}