嗨,我想仅通过过滤器功能

时间:2018-12-30 18:10:38

标签: javascript arrays object

假设我有一个列表,并且我要检查收入长度是否超过3位数字。

const list=[ {name:'Jhon',income:100},{name:'Ellen',income:100},{name:'joe',income:1500}
]

const newList=list.filter((sal) => sal.income.length > 3)

2 个答案:

答案 0 :(得分:1)

说明

好的,首先,在JavaScript和大多数其他语言中,您不能只拥有1000$这样的数据,而最好像我一样将这种数据存储为字符串。我的回答已经完成,只会在您的代码中导致错误。

然后,当然,有了我的答案,您想获取收入的数值,因此需要parseInt,此函数将忽略某些字符,例如本例中的'$',那么您可以检查收入是否大于1,000

另一个说明,我不确定您为什么用{name} => ...尝试了这种语法,但是不需要那样做,在这种情况下,根本不需要花括号。如果有的话,如果要像({name}) => ...那样做,那将从当前对象返回name属性,那么您甚至将无法访问income属性。

const list = [{
  name: 'Jhon',
  income: '1000$'
}, {
  name: 'Ellen',
  income: '1200$'
}, {
  name: 'joe',
  income: '1500$'
}]

const newList = list.filter(i => parseInt(i.income) > 1000);
console.log(newList);

答案 1 :(得分:1)

首先,属性值必须为整数,并且要删除美元符号:

const list = [ 
    {
        name:'Jhon', 
        income:1000
    }, {
        name:'Ellen',
        income:1200
    }, {
        name:'joe',
        income:1500
    }
];

现在,您只需要使函数起作用即可。这是您的操作方法:

 

const list = [ 
    {
        name:'Jhon', 
        income:1000
    }, {
        name:'Ellen',
        income:1200
    }, {
        name:'joe',
        income:1500
    }
];

var newList = list.filter(e => e.income > 1000);

newList.forEach((e, i) => newList[i] = e.income);

console.log(newList);