繁体   English   中英

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

[英]How to get values in object using a loop index

我有一个提交多个数据的 javascript 表单集,如果我获取所有发布数据,我有如下内容

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

在这种情况下,我有一个隐藏字段,用于保存提交的名称数量; 它的 3. 我希望能够在发布到 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);
        }

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

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

尝试这个。 应该是工作

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM