我在JS中有两个对象:
positions: {
top: { top: 10, left: 10 },
bottom: { top: 10, left: 10 },
left: { top: 10, left: 10 },
right: { top: 10, left: 10 },
},
positionAdjustments: {
top: { top: 0, left: 0 },
bottom: { top: 5, left: 5 },
left: { top: 0, left: 0 },
right: { top: 0, left: 0 },
},
我希望将它们组合起来,以便生成例如: -
positions: {
top: { top: 10, left: 10 },
bottom: { top: 15, left: 15 },
left: { top: 10, left: 10 },
right: { top: 10, left: 10 },
},
是否有一个lodash方法或一些优雅的方法来实现这一点而无需编写一些递归映射函数?例如:
positions.deepCombineValues(positionAdjustments);
答案 0 :(得分:1)
您可以迭代键和所需属性并调整位置。
var object = { positions: { top: { top: 10, left: 10 }, bottom: { top: 10, left: 10 }, left: { top: 10, left: 10 }, right: { top: 10, left: 10 } }, positionAdjustments: { top: { top: 0, left: 0 }, bottom: { top: 5, left: 5 }, left: { top: 0, left: 0 }, right: { top: 0, left: 0 } } };
Object.keys(object.positions).forEach(function (k) {
['top', 'left'].forEach(function (l) {
object.positions[k][l] += (object.positionAdjustments[k] || {})[l] || 0;
});
})
console.log(object.positions);

.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)
keys = Object.keys(positions)
const result = keys.map(key => (
{
top: positions[key].top + positionsAdjustments[key].top,
left: positions[key].left + positionsAdjustments[key].left,
}
));
那就是如果您不想使用lodash
并且只有top
left
top
left
right
bottom
{1}}个对象。可以改善这种方式