如何从JavaScript中的一系列对象中选取属性?

时间:2019-11-27 16:48:11

标签: javascript arrays object

我有此代码:

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)

但是我想我做错了

3 个答案:

答案 0 :(得分:1)

只需获取对象,然后获取所需属性

person = resultsBySalesperson.get(name);
sales = person.sales;
goals = person.goals;

答案 1 :(得分:1)

您确实需要Map.get才能按名称检索销售人员,但随后它返回一个纯JavaScript对象,您可以使用dot notation访问其属性。

例如:

const resultsBySalesperson = new Map([
  [
    "John",
    {
      "name": "John",
      "sales": 263,
      "goals": 10
    }
  ],
  [
    "Alice",
    {
      "name": "Alice",
      "sales": 506,
      "goals": 8
    }
  ]
]);

const john = resultsBySalesperson.get("John");

console.log(john.sales);
console.log(john.goals);

或者,您也可以使用方括号表示法(例如john["sales"])。

答案 2 :(得分:1)

您可以使用解构分配来获取所需的属性:

const {sales, goals} = resultsBySalesperson.get(name);