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);
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);
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']
添加回答
举报