0

I have a javascript formset that submits multiple data, if I am getting all the post data, I have something like the below

firstname1: "John",
lastname1: "Doe",
firstname2: "Mary",
lastname2: "Allinson",
firstname3: "David"
lastname3: "Mark",
eventDesctiption: "Lorem Ipsum...",
eventDate: "Lorem Ipsum..."

I have an hidden field that holds the number of names submitted, in this case; its 3. I want to be able to loop through the names and put them in an array of objects before posting to an API, I want to be able to achieve the below

{
eventDesctiption: "Lorem Ipsum...",
eventDate: "Lorem Ipsum...",
people: [
    {firstname: "John", lastname: "Doe"},
    {firstname: "Mary", lastname: "Allinson"},
    {firstname: "David", lastname: "Mark"},
    ]
}

I tried the below, but it seem to concatenate the index with the value, which is not what I want

peopleArray = new Array();
for(var i=1; i<=no_of_ben; i++){
            var peopleObject = {};
            
            peopleObject.firstname = data.firstname + 'i';
peopleObject.lastname = data.lastname + 'i';
            peopleArray.push(peopleObject);
        }

How to do this without concatenating the index

3 Answers3

2

const input = {
  firstname1: "John",
  lastname1: "Doe",
  firstname2: "Mary",
  lastname2: "Allinson",
  firstname3: "David",
  lastname3: "Mark",
  eventDescription: "Lorem Ipsum...",
  eventDate: "Lorem Ipsum..."
};

const output = {
  eventDescription: input.eventDescription,
  eventDate: input.eventDate,
  people: []
};

const peopleCount = 3; // You said you have this one somewhere
for (let i = 1; i <= peopleCount; i++) {
  const onePerson = {
    firstname: input['firstname' + i],
    lastname: input['lastname' + i]
  };
  output.people.push(onePerson);
}

console.log(output);
Anton
  • 2,669
  • 1
  • 7
  • 15
0

check if this works..

peopleArray = new Array();
for(var i=1; i<=no_of_ben; i++){
        var peopleObject = {};            
        peopleObject.firstname = data['firstname' + 'i'];
        peopleObject.lastname = data['lastname' + 'i'];
        peopleArray.push(peopleObject);
    }

replaced data.firstname + 'i' with data['firstname' + 'i']

shotgun02
  • 756
  • 4
  • 14
0

Try this. It should be work

peopleArray = new Array();
data = {
  firstname1: 'king', lastname1: 'James',
  firstname2: '2ndName', lastname2: '2ndLast',
  firstname3: 'alice', lastname3: 'bambam'
};

for(var i=1; i<=3; i++){
  var x = 'firstname';
  var y = 'lastname';
  var peopleObject = {};
  x = x + i;
  y = y + i;
  peopleObject.firstname = data[x];
  peopleObject.lastname = data[y];
  peopleArray.push(peopleObject);
}

console.log(peopleArray);
Kopi Bryant
  • 1,300
  • 1
  • 15
  • 30