0

I've flattened an array like this: let playerPool = [...new Set(array.flat(1))];
Which has an output like this: ["Howard Bell", "Matt Blair", "Dave Custer"]

How can I turn this into an array of objects? I want to update the above so the format is like this: [ {Name: "Howard Bell", Count: "0"}, {Name: "Matt Blair", Count: "0"}, {Name: "Dave Custer", Count: "0"} ]

I was trying to set this up by looping through the playerPool array but I get the following error: TypeError: Cannot set property 'Name' of undefined

let playerPool = [...new Set(array.flat(1))];
let playerObjects = [];

for(let i = 0; i < playerPool.length; i++) {
  playerObjects[i].Name = playerPool[i];
  playerObjects[i].Count = 0;
}

My goal is to be able to reference each property individually like this playerObjects[0].Count so I can later update the count value.

2 Answers 2

1

You forgot to create the object to which you want to assign the properties.

But you can do it more functional-style with map:

let playerPool = ["Howard Bell", "Matt Blair", "Dave Custer"];

let result = playerPool.map(name => ({name, count:0}));

console.log(result);

NB: if possible choose camelCase for your property names. There is a common practice to reserve PascalCase for constructor names ("classes").

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

Comments

0

You can try something like this,

let array1 = ["Howard Bell", "Matt Blair", "Dave Custer"];
let array2 = [];

array1.forEach(el => {
  array2.push({Name: el, count: 0});
});

console.log(array2);

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.