如何从 JavaScript 中的对象数组中选择属性?

我有这个代码:


const arraySalesperson = ["John", "Alice", "Bob", "John", "John", "Alice"];

const arraySales = [100, 420, 138, 89, 74, 86];

const arrayGoals = [1, 2, 3, 4, 5, 6];


// create a map

const resultsBySalesperson = new Map();


// traverse the list of salespersons

for (let i = 0; i < arraySalesperson.length; i++) {

  const name = arraySalesperson[i];

  

  // see if it already exists in the map

  let salesperson = resultsBySalesperson.get(name);


  if (!salesperson) {

    // if not, let's create an object now

    salesperson = {

      name: name,

      sales: 0,

      goals: 0

    };

    // store it in the map

    resultsBySalesperson.set(name, salesperson);

  }


  // update the object

  salesperson.sales += arraySales[i];

  salesperson.goals += arrayGoals[i];

}


// here you have the map ready with both sales and goal properly accumulated

console.info([...resultsBySalesperson.entries()]);


我需要使用属性 salesperson.sales 和 salesperson.goals。我该如何选择这些属性?我试过使用:


resultsBySalesperson.get(name)

resultsBySalesperson.get(salesperson.sales)

resultsBySalesperson.get(salesperson.goals)

但我觉得我做错了什么


婷婷同学_
浏览 241回答 3
3回答

幕布斯7119047

您确实需要Map.get按姓名检索销售人员,但随后它会返回一个纯 JavaScript 对象,您可以使用点表示法访问其属性。例如:const resultsBySalesperson = new Map([&nbsp; [&nbsp; &nbsp; "John",&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; "name": "John",&nbsp; &nbsp; &nbsp; "sales": 263,&nbsp; &nbsp; &nbsp; "goals": 10&nbsp; &nbsp; }&nbsp; ],&nbsp; [&nbsp; &nbsp; "Alice",&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; "name": "Alice",&nbsp; &nbsp; &nbsp; "sales": 506,&nbsp; &nbsp; &nbsp; "goals": 8&nbsp; &nbsp; }&nbsp; ]]);const john = resultsBySalesperson.get("John");console.log(john.sales);console.log(john.goals);或者,您也可以使用括号表示法(例如,john["sales"])。

宝慕林4294392

您可以使用解构赋值来获取所需的属性:const&nbsp;{sales,&nbsp;goals}&nbsp;=&nbsp;resultsBySalesperson.get(name);

慕无忌1623718

只需获取对象,然后获取想要的属性person = resultsBySalesperson.get(name);sales = person.sales;goals = person.goals;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript