[英]Accessing nested object values inside an array when using map to iterate over the array of objects
[英]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.