gpt4 book ai didi

javascript - 如何通过内部数组中的元素过滤对象数组 - Functional Programming Javascript

转载 作者:行者123 更新时间:2023-11-30 11:38:09 25 4
gpt4 key购买 nike

我仍在使用函数式编程:.forEach()、.map()、.filter()、.reduce()。

我正在应对新的挑战。

var bikes = [
{name: 'Cinelli Bolt', price: '2000', age: 1, singlespeed: 'yes', features: ['tubeless tires', 'disk brakes', 'carbon frame']},
{name: 'Cinelli Mash', price: '1700', age: 3, singlespeed: 'yes', features: ['gatorskin tyres', 'sram drivetrain', 'steel frame']},
{name: 'Specialized Langster', price: '1000', age: 1, singlespeed: 'no', features: ['two speed enclosed hub', 'bullbars', 'carbon frame']}
];

我正在尝试通过特定特征“碳纤维框架”过滤阵列。我正在考虑使用过滤器,但我对在 key.value 对中调用该功能感到困惑。

var justCarbonBikes = bikes.filter(function(bike) {
return bike.features['carbon frame'];
});

预期结果应该修改原始数组:

var bikes = [
{name: 'Cinelli Bolt', price: '2000', age: 1, singlespeed: 'yes', features: ['tubeless tires', 'disk brakes', 'carbon frame']},
{name: 'Specialized Langster', price: '1000', age: 1, singlespeed: 'no', features: ['two speed enclosed hub', 'bullbars', 'carbon frame']}
];

最佳答案

你快到了。使用 Array#indexOf 检查索引,您可以将其用作返回值。

return bike.features.indexOf('carbon frame') + 1;

var bikes = [{ name: 'Cinelli Bolt', price: '2000', age: 1, singlespeed: 'yes', features: ['tubeless tires', 'disk brakes', 'carbon frame'] }, { name: 'Cinelli Mash', price: '1700', age: 3, singlespeed: 'yes', features: ['gatorskin tyres', 'sram drivetrain', 'steel frame'] }, { name: 'Specialized Langster', price: '1000', age: 1, singlespeed: 'no', features: ['two speed enclosed hub', 'bullbars', 'carbon frame'] }],
justCarbonBikes = bikes.filter(function(bike) {
return bike.features.indexOf('carbon frame') + 1;
}),
bikesWithoutCarbon = bikes.filter(function(bike) {
return bike.features.indexOf('carbon frame') === -1;
});

console.log(justCarbonBikes);
console.log(bikesWithoutCarbon);
.as-console-wrapper { max-height: 100% !important; top: 0; }

ES6 与 Array#includes作为返回值。

var bikes = [{ name: 'Cinelli Bolt', price: '2000', age: 1, singlespeed: 'yes', features: ['tubeless tires', 'disk brakes', 'carbon frame'] }, { name: 'Cinelli Mash', price: '1700', age: 3, singlespeed: 'yes', features: ['gatorskin tyres', 'sram drivetrain', 'steel frame'] }, { name: 'Specialized Langster', price: '1000', age: 1, singlespeed: 'no', features: ['two speed enclosed hub', 'bullbars', 'carbon frame'] }],
justCarbonBikes = bikes.filter(b => b.features.includes('carbon frame')),
bikesWithoutCarbon = bikes.filter(b => !b.features.includes('carbon frame'));

console.log(justCarbonBikes);
console.log(bikesWithoutCarbon);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如何通过内部数组中的元素过滤对象数组 - Functional Programming Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43632253/

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