3 回答
TA贡献1719条经验 获得超6个赞
将您当前的结构转换为更方便的数据结构(JSON),如下所示:
const workers = [
{
name : 'David',
age : 41,
salary : 100
},
{
name : 'Juan',
age : 22,
salary : 80
},
{
name : 'Simon',
age : 33,
salary : 120
},
{
name : 'Lukas',
age : 50,
salary : 150
}
];
const olderThan30 = workers.filter(worker => worker.age > 30);
console.log(olderThan30);
// This console log will return this, an array of JSON objects that match the criteria of the filter function.
// [
// { name : "David", age : 41, salary : 100 },
// { name : "Simon", age : 33, salary : 120 },
// { name : "Lukas", age : 50, salary : 150 }
// ]
我希望这将有所帮助。
TA贡献1829条经验 获得超13个赞
就像@CharlieFish 提到的那样,您的数据结构不是正常的做事方式,而是您可以这样做:
const employees = [
{ name: 'David', age: 41, salary: 100 },
{ name: 'Simon', age: 33, salary: 120 },
{ name: 'Lukas', age: 50, salary: 150 },
];
const over30 = employees.filter(employee => employee.age > 30);
如果您确实需要坚持使用您的模式,您仍然可以这样做,但您必须过滤每个单独的数组:
const isOver30 = (_, i) => object1.age[i] > 30;
const thoseOver30 = {
name: object1.name.filter(isOver30),
age: object1.age.filter(isOver30),
salary: object1.salary.filter(isOver30)
}
...或更少重复:
const thoseOver30 = Object
.entries(object1)
.map(([prop, array]) => ({ [prop]: array.filter(isOver30) }))
.reduce((result, props) => Object.assign(result, props), {});
TA贡献1848条经验 获得超10个赞
一个易于理解的解决方案:
const maxAge = 30;
const object = {
name: ['David', 'Juan', 'Simon', 'Lukas'],
age: [41, 22, 33, 50],
salary: [100, 80, 120, 150]
};
const result = { name: [], age: [], salary: [] };
for (let i = 0; i < object.name.length; i++) {
if (object.age[i] <= maxAge) {
result.name = [...result.name, object.name[i]];
result.age = [...result.age, object.age[i]];
result.salary = [...result.salary, object.salary[i]];
}
}
console.log(result);
添加回答
举报