开发者

JavaScript Trivia: Function to combine two Array sets?

I have two Arrays of object, one has a set of options like this (the left side of the equation):

Id   Value
1    Red
2    Blue
3    Green

and another like this (the right side):

Id   Value
3    Green

And I need a "left join" (all left products and matching right) like开发者_StackOverflow this:

Id   Value   Selected
1    Red     
2    Blue    
3    Green   X

I would like to create a method with this setup (I put [] to note arrays)

var DisplayArray[] = AllColorsArray[].join(SelectedColors[]);

Is there anything like these already or maybe a JQuery plug-in that does this? It has to be common to provide a selection list with the saved options already checked.

EDIT:

It's really looking for simple SQL like operations on Arrays of objects, but with JavaScript.


use jquery extend, arrays are objects in js:

var object1 = {
  apple: 0,
  banana: {weight: 52, price: 100},
  cherry: 97
};
var object2 = {
  banana: {price: 200},
  durian: 100
};

$.extend(object1, object2);

In your case will be

var DisplayArray = $.extend(AllColorsArray ,SelectedColors);


You might be interested in LINQ to JavaScript for this sort of thing.


If you set up the arrays in such a way that the indexes are in the same position, you can use a two-dimensional array and then check to see if each dimension is equal. Something like this:

var ary = new Array();
ary[0] = new Array("Red","Blue","Green");
ary[1] = new Array(null, null, "Green");

for (var i in ary[0]) {
  alert(ary[0][i] == ary[1][i]); //True if they match, false if not.
}

EDIT
You can manually loop through and check them. You could even throw this in a function where you have to pass the selected and all color arrays. See below for example:

var AllColorsArray = [{"id":1,"value":"Red"},{"id":2,"value":"Blue"},{"id":3,"value":"Green"}];
var SelectedColors = [{"id":3,"value":"Green"}];
for (var ind in AllColorsArray) {
  for (var chkind in SelectedColors) {
    if (SelectedColors[chkind].id == AllColorsArray[ind].id) {
      AllColorsArray[ind] = $.extend(AllColorsArray[ind], SelectedColors[chkind]);
      break;
    }
  }
}
//To test:
for (var i in AllColorsArray) {
  alert(AllColorsArray[i].value + ': ' + AllColorsArray[i].selected);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜