我已经为这迭代苦了几天。无论我以何种方式使用这些方法,我都只能在没有其他算法的情况下映射或过滤“汽车”阵列。我想创建一个由品牌名称组成的对象数组,其中包括驱动程序名称,由品牌对象创建一个数组。
我尝试以不同的方式在代码中的不同位置混合这些方法,但我唯一要做的就是在内部没有品牌的映射数组。我还浏览了整个Stack,以寻求类似的问题和出色的解决方案。
var cars = [
{'brand': 'Ford'},
{'brand': 'Seat'},
{'brand': 'Opel'},
{'brand': 'Kia'},
{'brand': 'Mitsubishi'},
{'brand': 'Toyota'}
];
var drivers = [
{'name': 'Mark', 'car': 'Seat'},
{'name': 'John', 'car': 'Ford'},
{'name': 'Michael', 'car': 'Kia'},
{'name': 'Joe', 'car': 'Toyota'}
];
var assosiated = {};
console.log(assosiated);
那是我试图做的,但是不符合我的期望:
assosiated = cars.map(function (carss) {
var driver = drivers.filter(function (dri) {
return carss.brand === dri.car;
});
return carss.brand;
}).reduce(function (prev, curr) {
return prev + '\n' + curr;
});
我希望输出看起来像这样:
assosiated = {
"Ford": [
{"name": "John"}
],
"Seat": [
{"name": "Mark"}
],
"Opel": [],
"Kia": [
{"name": "Michael"}
],
"Mitsubishi": [],
"Toyota": [
{"name": "Joe"}
]
}
我也想使用上面写的所有这些方法。知道该怎么做才能对它进行排序吗?
答案 0 :(得分:3)
您还要处理对象文字,因此使用诸如.map()
,.filter()
,.reduce()
等数组方法只是解决方案的一部分。演示中有详细评论。
let cars = [
{'brand': 'Ford'},
{'brand': 'Seat'},
{'brand': 'Opel'},
{'brand': 'Kia'},
{'brand': 'Mitsubishi'},
{'brand': 'Toyota'}
];
let drivers = [
{'name': 'Mark', 'car': 'Seat'},
{'name': 'John', 'car': 'Ford'},
{'name': 'Michael', 'car': 'Kia'},
{'name': 'Joe', 'car': 'Toyota'}
];
// Declare empty object
let association = {};
/*
//A - for...of loop iterates through drivers array
Each iteration is obj = {'name':*, 'car':*}
//B - Obj association KEY = the value of 'car' obj['car']
VALUE = an array with an object inside
key='name', value = value of 'name'
*/
for (let obj of drivers) {//A
association[obj['car']] = [{'name': obj['name']}];//B
}
/*
//A - for...of loop iterates through cars array
Each iteration is obj = {'brand': *}
//B - if none of the keys of Object association matches the
values of cars array then add an empty array named as the
current "brand" value
*/
for (let obj of cars) { //A
if (!Object.keys(association).includes(obj['brand'])) {//B
association[obj['brand']] = [];
}
}
console.log(association);
答案 1 :(得分:2)
您只需要使用reduce
和filter
下面是我的例子
var cars = [
{'brand': 'Ford'},
{'brand': 'Seat'},
{'brand': 'Opel'},
{'brand': 'Kia'},
{'brand': 'Mitsubishi'},
{'brand': 'Toyota'}
];
var drivers = [
{'name': 'Mark', 'car': 'Seat'},
{'name': 'John', 'car': 'Ford'},
{'name': 'Michael', 'car': 'Kia'},
{'name': 'Joe', 'car': 'Toyota'}
];
var items = cars.reduce((result, {brand}) => {
result[brand] = drivers
.filter(({car}) => car === brand)
.map(({name}) => ({name}));
return result;
}, {})
console.log(items);
答案 2 :(得分:2)
在.map()
函数中,您只是在返回汽车的品牌。因此,从中返回的数组将如下所示:
[
'Ford',
'Seat',
'Opel',
...
]
传递给您的.reduce()
函数的是什么。
如果要使用指定格式的数组,请将函数更改为以下内容,它应该可以工作:
assosiated = cars.map(function (carss) {
var driver = drivers.filter(function (dri) {
return carss.brand === dri.car;
});
// return carss.brand; YOU'RE ONLY RETURNING THE BRAND
return {carss.brand: driver}
});