簡體   English   中英

使用map遍歷對象數組

[英]iterate over array of objects using map

我想遍歷對象數組並將wach對象傳遞給新數組。

但是結果始終是最后一個對象。

obj = [{ text: 'a'},{ text: 'b'}];
obj.map(funktion(item){
    result.push(Ext.merge({xtype: 'button'}, item));
});

// result is twice with text:'b'

它始終是最后一項。 這項工作如何消亡?

Ext.merge簡單地合並兩個對象,與JavaScript合並相同。

編輯1:所以我改為

obj = [{ text: 'a'},{ text: 'b'}];
btnsDest = obj.map(function(item){
     return Ext.merge({xtype: 'button'}, item);
});

還是一樣。 btnsDest [i] .text始終為“ b”

編輯2:所以我實際上有以下內容,但tagt不起作用

button = { xtype: 'button'};
obj = [{ text: 'a'},{ text: 'b'}];
btnsDest = obj.map(function(item){
     return Ext.merge(button, item);
});

因此,將var按鈕添加到回調中就可以了。

map的回調函數中,您需要返回轉換后的值(已mapped ):

obj = [{ text: 'a'},{ text: 'b'}];
obj.map(function(item){
    return Ext.merge({xtype: 'button'}, item);
});

以下是我在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));

輸出為:

[{"xtype":"button","text":"a"},{"xtype":"button","text":"b"}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM