Reputation: 5054
I want to iterate over an array of objects and pass wach object to a new array.
But the result is always the last object.
obj = [{ text: 'a'},{ text: 'b'}];
obj.map(funktion(item){
result.push(Ext.merge({xtype: 'button'}, item));
});
// result is twice with text:'b'
It's always the last item. How dies this work?
Ext.merge simply merges two objects, same as JavaScript merge.
EDIT 1: so I changed to
obj = [{ text: 'a'},{ text: 'b'}];
btnsDest = obj.map(function(item){
return Ext.merge({xtype: 'button'}, item);
});
Still the same. btnsDest[i].text is always 'b'
EDIT 2: so I actually had the following and tagt did not work
button = { xtype: 'button'};
obj = [{ text: 'a'},{ text: 'b'}];
btnsDest = obj.map(function(item){
return Ext.merge(button, item);
});
So adding the var button to the callback did the trick.
Upvotes: 0
Views: 131
Reputation: 3520
Within the map
's callback function you need to return the transformed value (mapped
):
obj = [{ text: 'a'},{ text: 'b'}];
obj.map(function(item){
return Ext.merge({xtype: 'button'}, item);
});
Following is what I tried at my end with node
and it works:
function merge_options(obj1,obj2){
var obj3 = {};
for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
return obj3;
}
button = { xtype: 'button'};
obj = [{ text: 'a'},{ text: 'b'}];
btnsDest = obj.map(function(item){
return merge_options(button, item);
});
console.log(JSON.stringify(btnsDest));
Output is:
[{"xtype":"button","text":"a"},{"xtype":"button","text":"b"}]
Upvotes: 1