如何使用循环索引获取对象中的值

How to get values in object using a loop index

我有一个提交多个数据的 javascript 表单集,如果我得到所有 post 数据,我有类似下面的内容

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

在本例中,我有一个隐藏字段,用于保存提交的姓名数量;其 3. 我希望能够在 post 到 API 之前遍历名称并将它们放入对象数组中,我希望能够实现以下

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

我尝试了下面的方法,但它似乎将索引与值连接在一起,这不是我想要的

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

如何在不连接索引的情况下执行此操作

检查这是否有效..

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

data.firstname + 'i' 替换为 data['firstname' + 'i']

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);

试试这个。应该是工作

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);