将对象数组合并为单个对象

时间:2020-05-14 15:14:27

标签: javascript node.js

我有一个对象数组,需要将它们组合成单个对象,但是在合并对象时,它们优先于某些值。

我收到如下错误。请建议

TypeError:Object.fromEntries不是函数

输入:

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'];

输出:

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

代码

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

1 个答案:

答案 0 :(得分:2)

Object.fromEntries包含在节点12中。我猜您正在使用旧版本。

如果没有Object.fromEntries,您可以做的是使用polyfill,或者只是尝试不使用语法糖,例如:

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));

这可以在您想到的最古老的JavaScript引擎中使用。