我有一个如下所示的JavaScript数组
var userMale = [];
var userData = [
{userId: "100", userName: "John", gender: "M"},
{userId: "101", userName: "Emma", gender: "F"},
{userId: "102", userName: "Alex", gender: "F"},
{userId: "103", userName: "Sam", gender: "M"}
]
我需要根据性别状况将所有userId放入不同的数组中,即所有男性都应位于userMale数组中
我已经编写了以下代码来实现这一目标。它有效,但是,我希望避免for和if循环
for(var i=0; i<userData.length; i++) {
if(userData[i].gender == "M") {
userMale.push(userData[i].userId);
}
}
console.log("userMale: ", userMale);
答案 0 :(得分:4)
您可以使用filter。
var userData = [
{userId: "100", userName: "John", gender: "M"},
{userId: "101", userName: "Emma", gender: "F"},
{userId: "102", userName: "Alex", gender: "F"},
{userId: "103", userName: "Sam", gender: "M"}
]
let userMale = userData.filter(data => {
return data.gender === "M"
})
console.log(userMale)
答案 1 :(得分:1)
您需要使用filter函数
var userData = [
{userId: "100", userName: "John", gender: "M"},
{userId: "101", userName: "Emma", gender: "F"},
{userId: "102", userName: "Alex", gender: "F"},
{userId: "103", userName: "Sam", gender: "M"}
]
let userMale = userData.filter(data => {
return data.gender === "M"
})
let userFemale = userData.filter(data => {
return data.gender === "F"
})
答案 2 :(得分:1)
您可以使用Underscore.js中的def year_info(year, yearly_weather):
try:
k = year
v = yearly_weather[k]
return "{:<8.0f}| {:<18.2f}| {:>12.2f} | {:>10.2f} | {:>10.0f}| {:>10.0f}" .format(k, *v)
except KeyError:
return "{:^8s}| {:^18s}| {:^12s} | {:^10s} | {:^10s} | {:^10s}".format(*['N/A']*6)
res = year_info(1965, yearly_weather)
'1965 | 43.00 | 33.00 | 0.27 | 1| 1'
返回列表中的值,但不包含真值测试(谓词)通过的元素。
reject
答案 3 :(得分:1)
由于您希望同时将元素过滤并投影到userId
上,因此使用Array.reduce
的方法似乎是最合适的方法。看到这里:
var userData = [
{userId: "100", userName: "John", gender: "M"},
{userId: "101", userName: "Emma", gender: "F"},
{userId: "102", userName: "Alex", gender: "F"},
{userId: "103", userName: "Sam", gender: "M"}
];
const convert = (data) => data.reduce((result, { userId, gender }) => {
if (gender === 'M') {
return result.concat(userId);
}
return result;
}, []);
var userMale = convert(userData);
console.log(userMale);
答案 4 :(得分:1)
使用原始JavaScript:
var userData = [
{userId: "100", userName: "John", gender: "M"},
{userId: "101", userName: "Emma", gender: "F"},
{userId: "102", userName: "Alex", gender: "F"},
{userId: "103", userName: "Sam", gender: "M"}
];
function getMaleFemale ()
{
// Create an array for each gender
let male = [], female = [];
// For each user, check if gender is F, if so, push id to female else to male
userData.forEach( user => ( user.gender === 'F' ? female : male ).push( user.userId ) );
// Return male and female
return { male, female };
}
// Usage example
let { male, female } = getMaleFemale();
// Do something with male and female
console.log( 'male :', male );
console.log( 'female :', female );
答案 5 :(得分:0)
FK82's approach的简洁版本。
let userMale = userData.reduce((result, user) =>
user.gender === 'M' ? result.concat(user.userId) : result
, [])