1

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]])
        ));
2
  • Your code works as expected repl.it/repls/ShockingSlateblueCylinders Commented May 14, 2020 at 15:21
  • I guess it is the node version. Our server node is 10.x. Commented May 14, 2020 at 15:26

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.