简体   繁体   English

使用map遍历对象数组

[英]iterate over array of objects using map

I want to iterate over an array of objects and pass wach object to a new array. 我想遍历对象数组并将wach对象传递给新数组。

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. Ext.merge简单地合并两个对象,与JavaScript合并相同。

EDIT 1: so I changed to 编辑1:所以我改为

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' btnsDest [i] .text始终为“ b”

EDIT 2: so I actually had the following and tagt did not work 编辑2:所以我实际上有以下内容,但tagt不起作用

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. 因此,将var按钮添加到回调中就可以了。

Within the map 's callback function you need to return the transformed value ( mapped ): map的回调函数中,您需要返回转换后的值(已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: 以下是我在node末尾尝试过的方法,它有效:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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