根据偏好将对象合并为一个
2020-01-12
68
我需要将优先于“X”和“AND”的所有 5 个对象合并为一个。
动态任何对象都可以为空。
输入
const cpc = {"L1":"NA","L2":"X","L3":"NA","L4":"NA","L3L4":"AND"}
const ph = {}
const pt = {"L1":"NA","L2":"NA","L3":"X","L4":"NA","L3L4":"AND"}
const cr = {"L1":"X","L2":"NA","L3":"NA","L4":"NA","L3L4":"NA"}
const mi = {}
输出:
const or = {"L1":"X","L2":"X","L3":"X","L4":"NA","L3L4":"AND"}
代码
我正在尝试合并 1&2、3&4 并将 1、2 的输出与 5 合并,但不确定是否有更好的方法
cr= Object.assign(...Object.keys(cpc).map(key => ({[key]: cpc[key] === "NA" ? ph[key] : cpc[key] })));
但是我收到错误 TypeError:如果对象为空,则无法将未定义或 null 转换为对象
3个回答
以下是 展平 输入数组并简化为结果对象的方法:
const cpc = {"L1":"NA","L2":"X","L3":"NA","L4":"NA","L3L4":"AND"};
const ph = {};
const pt = {"L1":"NA","L2":"NA","L3":"X","L4":"NA","L3L4":"AND"};
const cr = {"L1":"X","L2":"NA","L3":"NA","L4":"NA","L3L4":"NA"};
const mi = {};
const result = [cpc, ph, pt, cr, mi]
.map(Object.entries)
.flat().reduce((a, [k, v]) => ({
...a,
[k]: !a[k] || a[k] === 'NA' ? v : a[k]
}), {});
console.log(result);
Robby Cornelissen
2020-01-12
方法: 创建一个包含所有对象的数组,并循环遍历每个对象,将结果存储在临时对象中。检查临时对象是否已包含“X”和“AND”作为键值,否则创建新的键值对
const cpc = {"L1":"NA","L2":"X","L3":"NA","L4":"NA","L3L4":"AND"}
const ph = {}
const pt = {"L1":"NA","L2":"NA","L3":"X","L4":"NA","L3L4":"AND"}
const cr = {"L1":"X","L2":"NA","L3":"NA","L4":"NA","L3L4":"NA"}
const mi = {}
const objs = [cpc, ph, pt, cr, mi]
const tempObj = {}
objs.forEach((obj) => {
Object.keys(obj).forEach((key) => {
if (!(tempObj[key] == "X" || tempObj[key] == "AND")) {
tempObj[key] = obj[key]
}
})
})
console.log(tempObj)
Sunil Chaudhary
2020-01-12
您可以使用对象减少数组并提前检查值。
const
merge = (a, b) => Object.entries(b).reduce((o, [k, v]) => {
if (!['X', 'AND'].includes(o[k])) o[k] = v;
return o;
}, a),
cpc = { L1: "NA", L2: "X", L3: "NA", L4: "NA", L3L4: "AND" },
ph = {},
pt = { L1: "NA", L2: "NA", L3: "X", L4: "NA", L3L4: "AND" },
cr = { L1: "X", L2: "NA", L3: "NA", L4: "NA", L3L4: "NA" },
mi = {},
merged = [cpc, ph, pt, cr, mi].reduce(merge, {});
console.log(merged);
Nina Scholz
2020-01-12