为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

偶然的你 2023-03-24 17:11:39
我有一个提交多个数据的 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);        }如何在不连接索引的情况下执行此操作
查看完整描述

3 回答

?
一只斗牛犬

TA贡献1784条经验 获得超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);


查看完整回答
反对 回复 2023-03-24
?
喵喔喔

TA贡献1735条经验 获得超5个赞

尝试这个。应该是工作


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


查看完整回答
反对 回复 2023-03-24
?
慕雪6442864

TA贡献1812条经验 获得超5个赞

检查这是否有效..


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']


查看完整回答
反对 回复 2023-03-24
  • 3 回答
  • 0 关注
  • 127 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信