1

I have this code:

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()]);

I need to use the properties salesperson.sales and salesperson.goals. How can I pick those properties? Ive tried to use:

resultsBySalesperson.get(name)
resultsBySalesperson.get(salesperson.sales)
resultsBySalesperson.get(salesperson.goals)

But I think I'm doing something wrong

3 Answers 3

1

You indeed need Map.get to retrieve a salesperson by name, but then it returns a plain JavaScript object whose properties you can access using the dot notation.

For example:

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);

Alternatively, you can also use the bracket notation (e.g., john["sales"]).

Sign up to request clarification or add additional context in comments.

3 Comments

@GuilhermeStorti Do you have const john = resultsBySalesperson.get("John"); in your code? If so, it means that resultsBySalesperson does not have "John". Try the same syntax with some name that exists in the map.
I've tried to give the .get( ) a variable, like: const nameTest = resultsBySalesperson.get(name); and it gives me that nameTest is undefined
This will only happen if resultsBySalesperson does not have name as key.
1

Just get the object and then the wanted property

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

Comments

1

You could use destructuring assignment to get the required properties:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.