合并和重新排序两个对象数组的问题

时间:2015-06-13 23:48:56

标签: javascript arrays object reorderlist

我正在试图弄清楚如何合并两个对象数组。这就是我需要做的事情:

  • field属性是每个对象的唯一标识符
  • 输出需要仅包含originalArray中列出的对象,包括originalArraylocalStorageArray中不存在的对象
  • 需要维护localStorageArray的顺序,并注意以前的要求(订单应为:barbeefoobaz
  • 输出需要包含来自localStorageArray的以下属性值:hiddenwidthfield是一个给定项,因为它是标识符)
  • originalArray的所有其他属性需要在输出中维护

这是我对它的嘲笑:

var outputArray = [];

localStorageArray.forEach(function(localItem){
    originalArray.forEach(function(originalItem){
        if(originalItem.field === localItem.field){
            var item = JSON.parse(JSON.stringify(originalItem));
            item.hidden = localItem.hidden;
            item.width = localItem.width;
            outputArray.push(item);
        }
    });
});

Full JS Fiddle

我能够正确地排序和正确的属性,但我遇到的一个问题是originalArraylocalStorageArray中存在outputArray中不存在的对象,该对象不是包含在var originalArray = [ {field: "foo", hidden: true, sortable: false, template: "<div>#=text#</div>", width: "20px", propA: "a", propB: "b"}, {field: "bee", hidden: true, sortable: false, template: "=#text#", int: 4}, {field: "bar", hidden: false, sortable: false, template: "", width: "20%", propC: "C"}, {field: "baz", hidden: false, sortable: true, template: "<span>#=text#</span>", int: 3} ]; var localStorageArray = [ {field: "bar", hidden: false, sortable: false, width: "100px"}, {field: "foo", hidden: true, sortable: false, template: "<div>#=text#</div>", width: "40px"}, {field: "boo", hidden: true, sortable: true, template: "<div>Boo: #=text#</div>", width: "200px"}, {field: "baz", hidden: true, template: "baz:#=text#", width: "20px"} ];

对我的解决方案有任何建议吗?

以下是我的数组:

var desiredArray =  [
   {field: "bar", hidden: false, sortable: false, template: "", width: "100px", propC: "C"},
   {field: "bee", hidden: true, sortable: false, template: "=#text#", int: 4},
   {field: "foo", hidden: true, sortable: false, template: "<div>#=text#</div>", width: "40px", propA: "a", propB: "b"},
   {field: "baz", hidden: true, sortable: true, template: "<span>#=text#</span>", width: "20px", int: 3}
]

这是我想要的输出:

set input=
set /p input=[y/n]: %=%

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您希望覆盖hidden中同样存在于width中的那些对象的originalArraylocalStorageArray属性(2个对象被视为如果field属性相同,则相同)

    (function () {
    var fieldArray = localStorageArray.map(function(e) { return e.field; });
    originalArray.forEach(function(originalItem) {
      var index = fieldArray.indexOf(originalItem.field);
      var localItem; 
      if(index !== -1) {
        //it's also in localStorage, overwrite 
        localItem = localStorageArray[index];
        originalItem.hidden = localItem.hidden || originalItem.hidden;
        originalItem.width = localItem.width || originalItem.width;
        outputArray.push(originalItem);
      }
    })();

您也可以循环遍历localStorageArray并比较field属性

,而不是创建其他数组