2017-04-07 61 views
-1

我在JS兩個對象對象連接在一起地圖在JS(ES6)

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

爲什麼最後'left'是'0'? – ozil

+0

可能是一個錯字 – beniutek

+0

@ ozil sry是一個錯字! –

回答

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,只有具備topleftrightbottom對象中topleft鍵。可以probaly改善這種方式更多

+1

也謝謝!我希望lodash有一個內置的這種東西(在對象中加入鍵值),但我不認爲它是這樣,猜測它太具體了 –

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

Niiice!謝謝 –