Guilherme Storti
Guilherme Storti

Reputation: 155

How can I pick properties from an array of objects in JavaScript?

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

Upvotes: 1

Views: 95

Answers (3)

Clarity
Clarity

Reputation: 10873

You could use destructuring assignment to get the required properties:

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

Upvotes: 1

Alberto Trindade Tavares
Alberto Trindade Tavares

Reputation: 10356

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"]).

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386560

Just get the object and then the wanted property

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

Upvotes: 1

Related Questions