0

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.

1 Answer 1

1

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"}]
Sign up to request clarification or add additional context in comments.

2 Comments

Aarrrrg. I defined button as an object outside the callback and used button inside the callback merge. That does not work.
did that work? I am posting something which I tried with node at my end and it works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.