Search code examples
javascriptarraysobject

Create Object multiple objects from a array list


I have created a constructor function

  constructor(People) {
    this.PeopleName = People['Name'];
    this.PeopleId = People['Id'];
    this.PeopleGender = People['Gender'];
    this.Peopleunit = People['unit'];

const Name = ["Ashok", "Payal"];
const Id = ["1", "2"];
const Gender = ["M", "F"];

Now I have to map all the values that will return new People values as object.How can i pass all these values when we intialize an Object . Output will be somthing like this.

0:{Name:'Ashok', Id: '1', Gender: 'M', unit: '234'}
1:{Name:'Payal', Id: '2', Gender: 'f', unit: '234'}
    

Here Unit will be static.

I have tried for loop to do this but not works for me.Can anyone help me the acheive this objective


Solution

  • You can loop through and create object like this:

    const Name = ["Ashok", "Payal"];
    const Id = ["1", "2"];
    const Gender = ["M", "F"];
    const allPerson = [];
    
    Name.forEach((person, i) => {
        // You can instantiate your People object here
        allPerson.push({"Name": person, "Id": Id[i], "Gender": Gender[i], "unit": '234'})
    });
    
    console.log(allPerson);