Naim Mustafa
Naim Mustafa

Reputation: 344

Merge two array of objects into one by given key and duplicating other values

I have two arrays of objects that contain similar values

data = [array1, array2]

array1 = [{hour: "565", age: "21", id: "1", naban: "sdfsd"}, {hour: "515", age: "25", id: "2", naban: "sf"}]
array2 = [{hour: "56454", age: "21", id: "1", too: "898"}, {hour: "8979", age: "25", id: "2", too: "234234"},  {hour: "65465", age: "27", id: "6", too: "123"}]

and I have an array of which values of those two object set will be used for merge

keys= ['id', 'id']

I want to merge those objects and create one array of objects shown below:

result = [{hour: "565", hour2: "56454", age: "21", age2: "21", id: "1", too: "898", naban: "sdfsd"}, {hour: "515", hour2: "8979", age: "25", age2: "25", id: "2", too: "234234", naban: "sf"}, {hour: "65465", age: "27", id: "6", too: "123"} ]

Criteria:

This is what I did so far:

mergeOjects = (object, keys) => {
const sameKeys = Object.values(keys);
const data = Object.values(object);

if (data[0].length > data[1].length) {
  const yarrak = data[0].map((item, i) => {
    if (item[sameKeys[0]] === data[1][i][sameKeys[1]]) {
      return Object.assign({}, item, data[1][i]);
    }
    return Object.assign({}, item);
  });
  console.log({ sameKeys, data, yarrak });
} else {
  const yarrak = data[1].map((item, i) => {
    if (data[0][i]) {
      if (item[sameKeys[1]] === data[0][i][sameKeys[0]]) {
        return Object.assign({}, item, data[0][i]);
      }
    }
    return Object.assign({}, item);
  });
  console.log({ sameKeys, data, yarrak });
}};

it may need a bit of cleaning but I'm trying to get the logic work now, so sorry in advance. I was able to complete the second criteria but it overwrites the hour value instead of storing separately as it is in the example

Upvotes: 1

Views: 65

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386560

You could reduce the second array and take the wanted keys as common part for look up.

var array1 = [{ hour: "565", age: "21", id: "1", naban: "sdfsd" }, { hour: "515", age: "25", id: "2", naban: "sf" }],
    array2 = [{ hour: "56454", age: "21", id: "1", too: "898" }, { hour: "8979", age: "25", id: "2", too: "234234" }, { hour: "65465", age: "27", id: "6", too: "123" }],
    data = [array1, array2],
    keys = ['id', 'id'],
    merged = data[1].reduce((r, o) => {
        var temp = r.find(q => o[keys[0]] === q[keys[1]]);
        if (temp) {
            Object
                .entries(o)
                .forEach(([k, v]) => {
                    if (keys.includes(k)) return;
                    temp[k in temp ? k + 2 : k] = v;
                });
        } else {
            r.push({ ...o });
        }
        return r;
    }, data[0]);

console.log(merged);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 3

Related Questions