[英]How to merge an arrays of objects
我有两个 arrays 对象
const obj = {
teamRows: [
{name: 'Adam', admin_id: 3},
{name: 'Bob', admin_id: 4},
{name: 'Ivan', admin_id: 5},
],
roleRows: [
{title: 'Lead Bizdev', role_id: 5},
{title: 'Lead', role_id: 6},
{title: 'Integration', role_id: 7},
]
};
我想得到这样的东西。 teamRows 中的每一行都等于 roleRows 中的行
const newArr = [
{name: 'Adam', admin_id: 3, title: 'Lead Bizdev', role_id: 5},
{name: 'Bob', admin_id: 4, title: 'Lead', role_id: 6},
{name: 'Ivan', admin_id: 5, title: 'Integration', role_id: 7},
]
假设每个数组的长度相等,基于Array#map
的简单解决方案将是:
const obj = { teamRows: [ {name: 'Adam', admin_id: 3}, {name: 'Bob', admin_id: 4}, {name: 'Ivan', admin_id: 5}, ], roleRows: [ {title: 'Lead Bizdev', role_id: 5}, {title: 'Lead', role_id: 6}, {title: 'Integration', role_id: 7}, ] }; // For each teamRow, map it to a new object that is the merged // result of teamRow and the corresponding roleRow (by index) const newArr = obj.teamRows.map((teamRow, index) => ({...teamRow, ...obj.roleRows[index] })) console.log(newArr);
您可以减少 object 的所有值。
const object = { teamRows: [{ name: 'Adam', admin_id: 3 }, { name: 'Bob', admin_id: 4 }, { name: 'Ivan', admin_id: 5 },], roleRows: [{ title: 'Lead Bizdev', role_id: 5 }, { title: 'Lead', role_id: 6 }, { title: 'Integration', role_id: 7 }] }, result = Object.values(object).reduce((a, b) => a.map((o, i) => Object.assign({}, o, b[i]))); console.log(result);
.as-console-wrapper { max-height: 100%;important: top; 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.