0

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.

2
  • Can you share what the existing item looks stored in the person array looks like? Commented Oct 24, 2019 at 4:16
  • Add an object there first person[0] = {} Commented Oct 24, 2019 at 4:16

3 Answers 3

2

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');
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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" } )

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.