猿问

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

我有一个提交多个数据的 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);

        }

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


偶然的你
浏览 129回答 3
3回答

一只斗牛犬

const input = {&nbsp; firstname1: "John",&nbsp; lastname1: "Doe",&nbsp; firstname2: "Mary",&nbsp; lastname2: "Allinson",&nbsp; firstname3: "David",&nbsp; lastname3: "Mark",&nbsp; eventDescription: "Lorem Ipsum...",&nbsp; eventDate: "Lorem Ipsum..."};const output = {&nbsp; eventDescription: input.eventDescription,&nbsp; eventDate: input.eventDate,&nbsp; people: []};const peopleCount = 3; // You said you have this one somewherefor (let i = 1; i <= peopleCount; i++) {&nbsp; const onePerson = {&nbsp; &nbsp; firstname: input['firstname' + i],&nbsp; &nbsp; lastname: input['lastname' + i]&nbsp; };&nbsp; output.people.push(onePerson);}console.log(output);

喵喔喔

尝试这个。应该是工作peopleArray = new Array();data = {&nbsp; firstname1: 'king', lastname1: 'James',&nbsp; firstname2: '2ndName', lastname2: '2ndLast',&nbsp; firstname3: 'alice', lastname3: 'bambam'};for(var i=1; i<=3; i++){&nbsp; var x = 'firstname';&nbsp; var y = 'lastname';&nbsp; var peopleObject = {};&nbsp; x = x + i;&nbsp; y = y + i;&nbsp; peopleObject.firstname = data[x];&nbsp; peopleObject.lastname = data[y];&nbsp; peopleArray.push(peopleObject);}console.log(peopleArray);

慕雪6442864

检查这是否有效..peopleArray = new Array();for(var i=1; i<=no_of_ben; i++){&nbsp; &nbsp; &nbsp; &nbsp; var peopleObject = {};&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; peopleObject.firstname = data['firstname' + 'i'];&nbsp; &nbsp; &nbsp; &nbsp; peopleObject.lastname = data['lastname' + 'i'];&nbsp; &nbsp; &nbsp; &nbsp; peopleArray.push(peopleObject);&nbsp; &nbsp; }将data.firstname + 'i'替换为data['firstname' + 'i']
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答