MKN
MKN

Reputation: 497

Merge array of objects into single object

I have an array of objects which needs to be combined into single object but while merging it has a preference over certain values.

I get an error like below . Kindly suggest

TypeError: Object.fromEntries is not a function

Input:

let items =    [{"L4L5":"NA","L1":"NA","L2":"X","L6L7":"NA","L3":"NA"},
                 {"L4L5":"AND","L1":"X","L2":"X","L6L7":"NA","L3":"X"}]

let filter = ['X', 'AND', 'OR'];

Output:

 {"L4L5":"AND","L1":"X","L2":"X","L6L7":"NA","L3":"X"}

Code

  let out=  items.reduce((a, b) => Object.fromEntries(Object
                                       .keys(a)
                                       .map(k => [k, filter.includes(b[k]) ? b[k] : a[k]])
        ));

Upvotes: 1

Views: 128

Answers (1)

Object.fromEntries is included in node 12. I guess that you are using an old version.

What you can do without Object.fromEntries is to use a polyfill, or just try to do it without syntax sugar, like this:

let items = [
    {"L4L5":"NA","L1":"NA","L2":"X","L6L7":"NA","L3":"NA"},
    {"L4L5":"AND","L1":"X","L2":"X","L6L7":"NA","L3":"X"}
];
let filter = ['X', 'AND', 'OR'];

function merge(items, filter) {
    // Prepare the result object
    let result = {};
    // Loop through all the items, one by one
    for (let i = 0, item; item = items[i]; i++) {
        // For each item, loop through each key
        for (let k in item) {
            // If the result don't has this key, or the value is not one in preference, set it
            if (!result.hasOwnProperty(k) || filter.indexOf(result[k]) < 0) {
                result[k] = item[k];
            }
        }
    }
    return result;
}

console.log(merge(items, filter));

This works in the oldest JavaScript engine you can think of.

Upvotes: 2

Related Questions