需要从一系列对象中提取超过100,000个人的姓名

时间:2019-01-17 20:18:36

标签: javascript

我有很多人,他们的对象带有有关它们的详细信息。例如,“ Bob Cratchit”的年龄可能为30岁,拥有一套技能:“ JS,CSS,Python”,薪水为“ 113000”。我想先检查一下他的薪水是否超过100000,如果是,请返回他的名字和姓氏。

我尝试了.map和.filter的各种方法,甚至尝试嵌套它们。当我使用控制台时,.map可以正常工作,返回所有名称,而.filter返回薪水超过100000的人员的所有信息,但我似乎无法做到这两者。

let people = [{
    "id": 1,
    "firstName": "Frank",
    "lastName": "Herbert",
    "job": "Lead Software Engineer",
    "Skills": ["JavaScript", "C#", "SQL", "HTML", "CSS", "SCRUM 
Master"],
    "Salary": 120196
},
{
    "id": 2,
    "firstName": "Joan",
    "lastName": "Armorett",
    "job": "Jr Software Developer",
    "Skills": ["JavaScript", "HTML", "CSS"],
    "Salary": 70000
}

// This is the .map function, which will show me all of the names, 
regardless of their salary.
let answer = people.map((person) => {return person.firstName});

// This is the .filter function, which will show me all data, not 
just names on everyone with a salary of 100000 or higher.
let answer = people.filter((person) => {
    return person.Salary > 100000;
});

我想以某种方式兼得两者:仅显示收入在100000以上的人的结果,并且仅显示这些人的姓名,而不显示其中的其他数据。

2 个答案:

答案 0 :(得分:0)

下面的代码使用链接在一起的filter和map函数。 Filter返回一个包含薪金属性> 100000的所有对象的数组,而map接受从filter返回的数组,并返回对象的firstname和lastname属性。最后,使用扩展运算符(...)将数组扩展为文本。

let people = [{
   "id": 1,
   "firstName": "Frank",
   "lastName": "Herbert",
   "job": "Lead Software Engineer",
   "Skills": ["JavaScript", "C#", "SQL", "HTML", "CSS", "SCRUMMaster"],
   "Salary": 120196
},
{
   "id": 2,
   "firstName": "Joan",
   "lastName": "Armorett",
   "job": "Jr Software Developer",
   "Skills": ["JavaScript", "HTML", "CSS"],
   "Salary": 70000
}]
var t=people.filter((e)=>e.Salary>100000).map((e)=>e.firstName+" "+e.lastName)
console.log(...t)

答案 1 :(得分:-1)

您可以使用reduce来做到这一点:

    const peopleWhoMakeOverHundredThou = people.reduce((acc, el) => {
    if (el.Salary > 100000){
    const name = `${el.firstName} ${el.lastName}`
    acc.push(name);
     }
    return acc;
    },[])
    console.log(peopleWhoMakeOverHundredThou)

如果您只希望一个更高,并且只想返回一个字符串而不是任何数组,则可以进行如下调整:

    const peopleWhoMakeOverHundredThou = people.reduce((acc, el) => {
    if (el.Salary > 100000){
    const name = `${el.firstName} ${el.lastName}`
    acc+=name;
     }
    return acc;
    },'')
    console.log(peopleWhoMakeOverHundredThou)