JQuery $ .extend不能像我期望的那样工作:如何正确编码?

时间:2010-11-06 17:11:13

标签: javascript jquery extend

Here是JQuery扩展页面。

我期望这样做是采用两个数组,将它们连接在一起并为每个结果数组元素创建统一的属性。如何让它按预期工作?

var a = [];
a.push({ "id": 1, "text": "one" });
a.push({ "id": 2, "text": "two" });
a.push({ "id": 3, "text": "three" });
var b = [];
b.push({"id":3 , "selected":true});
var c = [];
$.extend(c,a,b);

我期望得到的数组包括:

{ "id": 1, "text": "one", "selected": false }
{ "id": 2, "text": "two", "selected": false }
{ "id": 3, "text": "three", "selected": true }

但是它似乎只是将第一个数组复制到第二个数组之上:

{ "id": 3, "text": null, "selected": true }
{ "id": 2, "text": "two" }
{ "id": 3, "text": "three" }

文档包括:

当我们向$ .extend()提供两个或多个对象时,所有对象的属性都会添加到目标对象中。

我做错了什么,或者我将如何做到这一点?

编辑:Jball的建议已实施:

var a = [];
a.push({ "id": 1, "text": "one" });
a.push({ "id": 2, "text": "two" });
a.push({ "id": 3, "text": "three" });
var b = [];
b.push({ "id": 3, "selected": true });
var c = [];
for (var index = 0; index < a.length; index++) {
   var tempresult = {};
   var tempb = b.filter(
      function (ele, idx, collection) {
         return (collection[idx].id == index + 1);
      });
   if (tempb.length == 0)
      tempb = [{ "id": index + 1, "selected": false }];
   $.extend(tempresult, a[index], tempb[0]);
   c.push(tempresult);
} 

产生

[{"id":1, "selected":false, "text": "one"},
 {"id":2, "selected":false, "text": "two"},
 {"id":3, "selected":true,  "text": "three"}]

这就是答案。现在我想知道它是否可以清理一下。

1 个答案:

答案 0 :(得分:1)

我不确定你是否注意到它,但$.extend()函数用于对象的属性,而不是数组的元素。

您似乎需要创建一个循环遍历数组的函数,并在匹配元素上调用$.extend()以获得所需的结果。您必须决定是否要添加或忽略第二个数组中的非匹配元素。

问题是jQuery不知道你的数组中的哪些元素是匹配的,所以通过索引匹配它们,虽然我不确定为什么第一个项的结果有"text": "three"而不是{{1除非它在根据索引执行"text": "one"之后尝试通过单个项属性进行匹配。