简体   繁体   中英

iterate over array of objects using map

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.

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"}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM