如何使用_unionBy()将两个文件的内容合并在一起;

时间:2018-11-05 07:26:13

标签: reactjs lodash

    var original = [
      { label: 'private', value: 'private@johndoe.com', id: 21 }
    ];

    var update = [
      { label: 'private', value: 'me@johndoe.com', uploadId: 'jdsnl' }
    ];

    var result = _.unionBy(original, update, "label");

我希望结果是

[{label: 'private', value: 'private@johndoe.com', id: 21, uploadId: 'jdsnl' }]

我该如何实现?

2 个答案:

答案 0 :(得分:0)

unionBy不会帮助您,但是groupBymerge会帮助您。

(我已经在示例输入中添加了多个数据,以证明它可以正常工作。)

_ = require("lodash");

var original = [
  {
    label: "private",
    value: "private@johndoe.com",
    id: 21,
  },
  { label: "public" },
  { label: "test3" },
];

var update = [
  {
    label: "private",
    value: "me@johndoe.com",
    uploadId: "jdsnl",
  },
  { label: "test3", value: "update3" },
];

// Use groupBy over the merged originals and updates
// (in this order, so the groups in the output have
// the correct application order)
// to get an object mapping `label` to each group,
// then unwrap the object to just get a list of groups
// using values. 
var groups = _.values(
  _.groupBy(_.concat(original, update), "label"),
);

// map over the groups (lists), applying merge so that
// it is called e.g. for a group [a, b, c] with the
// arguments [{}, a, b, c], so that properties are merged
// into a new object from the original, then the update
// objects.
var merged = _.map(groups, group =>
  _.merge.apply(null, _.concat([{}], group)),
);
console.log(merged);

输出为

[ { label: 'private',
    value: 'me@johndoe.com',
    id: 21,
    uploadId: 'jdsnl' },
  { label: 'public' },
  { label: 'test3', value: 'update3' } ]

符合预期。

答案 1 :(得分:0)

可以使用_.unionWith来完成此操作,

const A = [{ label: 'private', value: 'private@johndoe.com', id: 21 }];
const B = [{ label: 'private', value: 'me@johndoe.com', uploadId: 'jdsnl' }];

console.log(_.unionWith(A, B, (a,b) => _.defaults(b, {uploadId: a.uploadId})))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

不带破折号的另一种方法是使用mapfind

var original = [{ label: 'private', value: 'private@johndoe.com', id: 21 }];
var update = [{ label: 'private', value: 'me@johndoe.com', uploadId: 'jdsnl' }];

const result = original.map(x => {
  let f = update.find(y => y.label == x.label)
  return f ? Object.assign(x, {uploadId: f.uploadId}) : x
})

console.log(result)