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:
- Id like to keep all the information that is not in the keys array eg. if you look at the result array you will see hour and hour2 values.
- If keys don't match it will push the object as it is (eg. 3rd item in the result array)
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
hourbut only oneage? because of the different values?keysarray, how should it be if the keys are different? what should happen? i would understand if the group has more than one key, but if the same, the array makes no sense.