Dojo lang.mixin for 循环仅将最后一项写入对象

Dojo lang.mixin for loop only writing last item to object

我正在使用 dojo lang.mixin 将项目写入对象,但它似乎只将最后一个 key:value 写入对象。这让我觉得 lang.mixin 一次只写一个 key:value。有没有办法继续向对象附加 key:values?

for (var i = 0; i < selection.length; ++i) {
   lang.mixin(myObj, {
     selection[i].Type: selection[i].Name //always gives me last index in loop
   })
}

向对象添加属性时,属性必须是唯一的。

lang.mixin用于用源对象更新目标对象。如果 属性 "name" 与源匹配,则 属性 会更新,否则 属性 会添加到目标。嵌套对象不会混合。例如:

var a = { 
    name:"John",
    account : { type : "student", email : "a@xyz.com" }
};
var b = { 
    Age: "18 yrs",
    account: { phone : "66589956" }
};
lang.mixin(a, b); // here the type and email will be lost for account property

在你的情况下,如果你认为 selection[i].Type 是 "type" 那么你的代码将表现如下

for (var i = 0; i < selection.length; ++i) {
    lang.mixin(myObj, {
        "type" : selection[i].Name
    });
}

因此相同的 属性 将在循环的每个循环中更新,除非 selection[i].Type 值不同。

require(["dojo/_base/lang"], function(lang){
  var selection = [ { Type:"A", Name:"Letter A" },
                    { Type:"B", Name:"Letter B" },
                    { Type:"C", Name:"Letter C" },
                    { Type:"D", Name:"Letter D" }
                   ];
  
  var myObj = {};
  for (var i = 0; i < selection.length; ++i) {
     var tmp = {};
     tmp[selection[i].Type] = selection[i].Name;
     lang.mixin(myObj, tmp);
  }
  console.log(myObj);
});
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.11.2/dojo/dojo.js"></script>