# 合并数组，取相应的key并传参，详细看正文，求解

demon_369
• 10

``````let a = [
{
section: '',
cost: '',
paycost: '',
},
];
let b = [
{
section: '张三',
cost: '1',
paycost: '2',
paytime: '3',
desc: '4',
},
{
section: '李四',
cost: '11',
paycost: '22',
paytime: '33',
desc: '44',
},
{
section: '王五',
cost: '111',
paycost: '222',
paytime: '333',
desc: '444',
},
];
``````

``````    {
section: '张三',
cost: '1',
paycost: '2',
},
{
section: '李四',
cost: '11',
paycost: '22',
},
{
section: '王五',
cost: '111',
paycost: '222',
},``````

## 方法一

@林枫 的方法，只不过里面有一点需要改进：不要在 `b.map` 循环里每次去取 `Object.keys(a[0])`，提前一次取好重复用就行。

``````const res = (() => {
const keys = Object.keys(a[0]);
return b.map(it => Object.fromEntries(keys.map(key => [key, it[key]])));
})();
console.log(res);``````

## 方法二「推荐」

``import _ from "lodash";``
``````const result = (() => {
const keys = Object.keys(a[0]);
return b.map(it => _.pick(it, keys));
})();

console.log(result);``````

## 方法三

``````const result2 = (() => {
const keys = new Set(Object.keys(a[0]));
b.forEach(it =>
Object.keys(it)
.filter(key => !keys.has(key))
.forEach(key => delete it[key])
);
return b;
})();

console.log(result2);``````

``````const result3 = (() => {
const removeKeys = (keys => {
Object.keys(a[0]).forEach(key => keys.delete(key));
return keys;
})(new Set(Object.keys(b[0])));

b.forEach(it => removeKeys.forEach(key => delete it[key]));
return b;
})();

console.log(result3);``````