Md Dilshadur Rahman
Md Dilshadur Rahman

Reputation: 88

How to populate an array in javascript if I want to have multiple elements for a single index of an array

How to populate an array in javascript when I want to store multiple elements in a single index?

I want to populate an array in Javascript. What I am trying to do is to store both firstName and lastName of a person in an array index. I am trying to do person[0].firstName = 'Dilshadur'; and then person[0].secondName = 'Rahman'; but It's not working and I think this is not the correct syntax to do so.

person[0].firstName.fill('Md Dilshadur Rahman'); person[0].lastName = 'Rahman'; person[1].firstName = 'Tabassum Monia'; person[1].lastName = 'Disha';

I am getting in the console something like this: "Uncaught TypeError: Cannot read property 'firstName'", I think this because of the wrong syntax and I am not being able to find the correct syntax.

Upvotes: 0

Views: 51

Answers (3)

Lightning
Lightning

Reputation: 405

You would have to have an object assigned to each index of the array, and each of those objects would have the firstName and lastName properties.

Ex:

let person = [];
person[0] = {firstName: 'Dilshadur', lastName: 'Rahman'};
person[1] = {firstName: 'Tabassum Monia', lastName: 'Disha'};

You should consider creating a separate class or something where this structure is defined.

class Person {
    constructor(first, last) {
        this.firstName = first;
        this.lastName = last;
    }
}

let person = [];
person[0] = new Person('Dilshadur', 'Rahman');
person[1] = new Person('Tabassum Monia', 'Disha');

Upvotes: 2

Yasser Mas
Yasser Mas

Reputation: 1682

You can create array of objects

  person = [];
  person[0] = { firstName: "abc" , lastName: "def" } :

  Or you can push values to it by 
  person.push( { firstName: "abc" , lastName: "def" } )

Upvotes: 1

nodediggity
nodediggity

Reputation: 2488

You need to store an array of objects in that case.

const results = [
   { firstName: 'clark', lastName: 'kent' },
   { firstName: 'bruce', lastName: 'wayne' }
]

You can then use the spread operator to populate the entire index.

const newResults = [
   { firstName: 'peter', lastName: 'parker' },
   ...results
]

You can also push to your array, however it is good practice to not mutate your data and instead create an updated copy of it.

Upvotes: 1

Related Questions