I would like to add multiple elements that all have the same value to an array of objects Something like '.push()' but with a count. I know I can do array.push(a, b, c), but I want to be able to do something like:
person {
firstName: string;
lastName: string;
age: number;
}
people: Person[];
numberPeople: number;
// some calculation to generate numberPeople, example: 23
person.push( {firstName: '', lastName: 'Smith', age: 0}, NumberPeople)
I know I can use a loop structure (for (i=0; i<NumberPeople;i ) person.push) but that gets cumbersome. Is there an easier way? I'm relatively new to JavaScript and TypeScript.
I've tried .fill() but that doesn't let me specify values.
thanks,
I know I can create my own function ( mpush(obj, count) ) but I would rather use something more elegant and standard, if there is something.
CodePudding user response:
You can use the inbuilt fill()
method by first creating an Array
of the right size and then populating it with a value multiple times.
interface person {
firstName: string;
lastName: string;
age: number;
}
const samplePerson = {firstName: '', lastName: 'Smith', age: 0}
const people = Array(numberPeople).fill(samplePerson)
CodePudding user response:
You can use fill and here is an example using TypeScript.
type Person = {
firstName: string;
lastName: string;
age: number;
}
let people: Person[]=[];
// you can replace 10 with the calculation
let numberPeople: number = 10;
// this will create an array with all elments having {firstName: '', lastName: 'Smith', age: 0}) as values, with length of numberPeople
people = Array(numberPeople).fill({firstName: '', lastName: 'Smith', age: 0})
CodePudding user response:
I would count the additions live, as I am adding more people.
Granted it is a zero based array, so 1st would be 0, the index in the array.
let people = [];
let samples = 23;
for (let i = 0; i < samples; i )
{
let person = { firstName: 'Bob_' i, lastName: 'Smith', age: 0 };
people.push( { index: people.length, person } );
}
// We should now have the 23 people needed.
console.log(people.length); // 23
// Example of the first added.
console.log(people[0]);
/* Results:
{
"index": 0,
"person": {
"firstName": "Bob_0",
"lastName": "Smith",
"age": 0
}
}
*/
CodePudding user response:
You can use .fill()
indeed:
const NumberPeople = 3;
const people = Array(NumberPeople).fill({firstName: '', lastName: 'Smith', age: 0});
console.log(people);
// notice the above method places the same person in all positions
console.log(people[2].age); // will log 0
people[1].age = 4;
console.log(people[2].age); // will log 4
//
//
// if all values being the same object is a problem, you can use .map:
const people2 = [...Array(NumberPeople)].map(_ => ({firstName: '', lastName: 'Smith', age: 0}));
console.log(people2);
console.log(people2[2].age); // will log 0
people2[1].age = 4;
console.log(people2[2].age); // will log 0