合并数组,取相应的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',
    },
回复
阅读 210
2 个回答

方法一

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

另外,reduce 很好,效率也不错,不过从语法上来说,可以用 map + Object.fromEntries() 来写逻辑会更清楚

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

方法二「推荐」

说实在的,处理数据我还是比较喜欢用 Lodash

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

对于当前这个问题,由于 b 中的属性固定,可以提前把需要删除的 keys 算好,

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);
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',
    },
];
const res = b.map(item => Object.keys(a[0]).reduce((c,d) =>({...c,[d]:item[d]}) ,{}))
你知道吗?

宣传栏