我想從一個已經存在的對象和數組中創建一個具有修改過的屬性名稱的對象。如何從數組和已有對象創建新對象?
var ExistingObj = {'123' : 50, '456' : 60, '789' : 90};
var idsArr = ['123', '456', '789'];
我想創建一個對象包含以下內容的數組:
var newArr = [{id : '123', amount: 50}, {id: '345', amount: 60}, {id:'789' : 90}];
我試圖映射像這樣,它不工作:
var existingObj = {'123' : 50, '456' : 60, '789' : 90};
var idsArr = ['123', '456', '789'];
function formatArr(idsArr, existingObj){
var obj = {};
var container = [];
_.map(idsArr, function(id){
obj.id = id;
obj.amount = existingObj[id];
container.push(obj);
});
return container;
}
和結果是:
container = [{'id' : '789', 'amount' : 90}, {id : '789', 'amount' : 90}, {id:'789', 'amount' : 90}];
任何想法?
感謝您的信息!我能夠以這種方式工作: 函數formatArr(idsArr,existingObj,fn)var newArr = _.map(idsArr,function(id){ return {id:id,amount:existingObj [id] } }); fn(newArr); } – user3476766