Mladen Mladen - 3 months ago 16
Javascript Question

How to add one array object to another 2 dimensional array by key with lodash

I have one array of messages for example:

[{
day: "1",
msgs: [{day: "1", id: 1, msg: 'txt'}]
},{
day: "2",
msgs: [{day: "2", id: 2, msg: 'txt'}]
}]


and I receive new messages from server in this format:

[
{day: "1", id: 3, msg: 'txt'},
{day: "1", id: 4, msg: 'txt'},
{day: "2", id: 5, msg: 'txt'},
{day: "3", id: 6, msg: 'txt'}
]


And I need to merge new values into old messages array. And this is the example of results I need.

[{
day: "1",
msgs: [{day: "1", id: 1, msg: 'txt'},
{day: "1", id: 3, msg: 'txt'},
{day: "1", id: 4, msg: 'txt'}]
},{
day: "2",
msgs: [{day: "2", id: 2, msg: 'txt'},
{day: "2", id: 5, msg: 'txt'}]
},{
day: "3",
msgs: [{day: "3", id: 6, msg: 'txt'}]
}]


I spend 5h on stack overflow to find similar case but I did not found it.
I've already tried using lodash functions groupBy and forEch and it did not work.
The important thing is if NEW DAY comes from server to add that day in old results.

Answer

You can do this in pure js with forEach() and find()

var ar1 = [{
    day: "1",
    msgs: [{day: "1", id: 1, msg: 'txt'}]
},{
    day: "2",
    msgs: [{day: "2", id: 2, msg: 'txt'}]
}];

var ar2 = [
    {day: "1", id: 3, msg: 'txt'},
    {day: "1", id: 4, msg: 'txt'},
    {day: "2", id: 5, msg: 'txt'},
    {day: "3", id: 6, msg: 'txt'}
];

ar2.forEach(function(o) {
  var e = ar1.find((a) => a.day == o.day);
  (e != undefined) ? e.msgs.push(o) : ar1.push({day: o.day,msgs: [o]});
})

console.log(ar1)

Comments