Lit Aiy Lit Aiy - 5 months ago 9
Javascript Question

Process this array of objects and combine some into one

I have this object.

var orig_array = [
{ "MSG_ID": { "lgth": "1", "payload": 0 } },
{ "STATE_1": { "lgth": "1", "payload": "XX" } },
{ "STATE_2": { "lgth": "1", "payload": "XXX" } },
{ "MSG_ID": { "lgth": "1", "payload": 1 } },
{ "STATE_1": { "lgth": "1", "payload": "X" } },
{ "STATE_2": { "lgth": "1", "payload": "XX" } },
{ "STATE_3": { "lgth": "6", "payload": "XXX" } },
{ "MSG_ID": { "lgth": "1", "payload": 2 } },
{ "STATE_1": { "lgth": "1", "payload": "XXXX" } }
];


I want to reduce the number of objects by grouping a few related objects into a single one.

The resulting array should look like this;

var processed_array = [
{ "MSG_ID": { "lgth": "1", "payload": 0 }, "STATE_1": { "lgth": "1", "payload": "XX" },"STATE_2": { "lgth": "1", "payload": "XXX" } },
{ "MSG_ID": { "lgth": "1", "payload": 1 },"STATE_1": { "lgth": "1", "payload": "X" },"STATE_2": { "lgth": "1", "payload": "XX" },"STATE_3": { "lgth": "6", "payload": "XXX" } },
{ "MSG_ID": { "lgth": "1", "payload": 2 },"STATE_1": { "lgth": "1", "payload": "XXXX" } }
];


In
orig_array
, there are 3 objects with
"MSG_ID"
. The subsequent
"STATE_X"
objects are combined into the above
"MSG_ID"
object. I have been staring at this problem for some time. Anyone can help or give some hints as a head-start?

Answer

You could use Array#reduce and look for 'MSG_ID' as a group change.

var array = [{ "MSG_ID": { "lgth": "1", "payload": 0 } }, { "STATE_1": { "lgth": "1", "payload": "XX" } }, { "STATE_2": { "lgth": "1", "payload": "XXX" } }, { "MSG_ID": { "lgth": "1", "payload": 1 } }, { "STATE_1": { "lgth": "1", "payload": "X" } }, { "STATE_2": { "lgth": "1", "payload": "XX" } }, { "STATE_3": { "lgth": "6", "payload": "XXX" } }, { "MSG_ID": { "lgth": "1", "payload": 2 } }, { "STATE_1": { "lgth": "1", "payload": "XXXX" } }],
    grouped = array.reduce(function (r, a) {
        var key = Object.keys(a)[0];
        if (key === 'MSG_ID') {
            r.push({});
        }
        r[r.length - 1][key] = a[key];
        return r;
    }, []);

console.log(grouped);