如何在JavaScript ES6中合并含不同键对的对象数组?
合并两个含不同键对的对象数组(JavaScript)
你之前用扩展语法的问题在于,它只是把两个数组的元素拼接到一起,并没有合并每个元素内部的对象属性。咱们可以利用数组的map方法结合对象扩展语法(或者Object.assign)来实现需求,前提是两个数组中对应位置的元素属于同一个问题(这点你的示例里是满足的)。
方法一:使用对象扩展语法(ES6+)
const listOfQuestions = [{ question1: { important: true } }, { question2: { important: false } }]; const listOfAnswers = [{ question1: { answer: false } }, { question2: { answer: true } }]; const result = listOfQuestions.map((questionObj, index) => { // 获取当前对象的唯一键(比如"question1") const questionKey = Object.keys(questionObj)[0]; // 合并对应问题的重要性和答案属性 return { [questionKey]: { ...questionObj[questionKey], ...listOfAnswers[index][questionKey] } }; }); console.log(result); // 输出:[{ "question1": { "important": true, "answer": false } }, { "question2": { "important": false, "answer": true } }]
方法二:使用Object.assign
如果需要兼容稍旧的环境,可以用Object.assign替代扩展语法:
const result = listOfQuestions.map((questionObj, index) => { const questionKey = Object.keys(questionObj)[0]; return { [questionKey]: Object.assign( {}, questionObj[questionKey], listOfAnswers[index][questionKey] ) }; });
代码说明
map方法遍历listOfQuestions的每个元素,同时拿到当前元素的索引index;Object.keys(questionObj)[0]获取每个对象里的唯一键(因为你的每个数组元素都是单个键的对象);- 最后用扩展语法/
Object.assign把对应问题的important和answer属性合并到同一个对象里,再包装成原有的键值结构。
内容的提问来源于stack exchange,提问作者Phoenix
相关产品推荐
相关产品推荐

