Как объединить содержимое двух файлов в одном с _unionBy (); - PullRequest
0 голосов
/ 05 ноября 2018
    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 голосов
/ 05 ноября 2018

Это можно сделать с помощью _. 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>

Другой способ без lodash был бы с map & find:

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)
0 голосов
/ 05 ноября 2018

Просто unionBy вам не поможет, но groupBy и merge помогут.

(Я добавил несколько данных в пример ввода, чтобы доказать, что он работает как задумано.)

_ = 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' } ]

как и ожидалось.

...