2017-09-13 58 views
0

我想合併兩個對象與包含對象..其中包含一個對象數組..你有想法。但是,我的代碼只是沒有產生預期的結果,我不能why..probably理解,因爲我只是用lodash開始,我失去了一些東西明顯深度合併兩個JavaScript對象lodash/vanilla

下面是我要合併

var original = { 
    a: "bbbb", 
    Id: 1, 
    b: { 
     a: "bbb", 
     Id: 2 
    }, 
    c: "aaa", 
    d: [ 
     { 
      a: "bbbb", 
      Id: 1, 
      b: { 
       a: "bbb", 
       Id: 2 
      }, 
      c: "aaa" 
     }, 
     { 
      a: "bbbb", 
      Id: 2, 
      b: { 
       a: "bbb", 
       Id: 3 
      }, 
      c: "aaa" 
     } 
    ] 
}; 

var source = { 
    a: "aaa", 
    Id: 1, 
    b: { 
     a: "aaa", 
     Id: 2 
    }, 
    c: null, 
    d: [ 
     { 
      a: "aaa", 
      Id: 1, 
      b: { 
       a: "aaa", 
       Id: 2 
      }, 
      c: null 
     }, 
     { 
      a: "aaa", 
      Id: 2, 
      b: { 
       a: "aaa", 
       Id: 3 
      }, 
      c: null 
     } 
    ] 
}; 
兩個對象

結果對象應該只包含「aaa」作爲值並且不包含空值(從「source」獲取值,除非它爲null,並且不拷貝數組,只是將對象合併到其中)。我的代碼合併對象就好了......但是,當它到達對象數組時,它無法產生正確的結果

結果應該是:

{"a":"aaa", 
"Id":1, 
"b": 
    { 
    "a":"aaa", 
    "Id":2 
    }, 
    "c":"aaa", 
    "d": 
    [ 
     { 
     "a":"aaa", 
     "Id":1, 
     "b": 
     { 
     "a":"aaa", 
     "Id":2 
     }, 
     "c":"aaa" 
    }, 

{ 「一」: 「AAA」, 「ID」:2, 「B」: { 「一」: 「AAA」, 「ID」:3 }, 「C」: 「AAA」 } ]}

這裏是我的代碼:https://jsfiddle.net/yodfcn6e/

謝謝!

+0

請添加想要的結果。 –

+0

你想如何合併數組?你是否假設數組將具有相同的長度,並且你想要兩兩合併條目? – skirtle

+1

我編輯你的代碼是可讀的。你能以相同的格式添加所需的結果嗎?仍然不確定我的小提琴是否回答你想要的。 – DrewT

回答

1

您可以迭代對象的鍵並僅在目標具有null值時更新。

function update(source, target) { 
 
    Object.keys(source).forEach(function (k) { 
 
     if (target[k] === null) { 
 
      target[k] = source[k]; 
 
      return; 
 
     } 
 
     if (source[k] && typeof source[k] === 'object') { 
 
      update(source[k], target[k]); 
 
     } 
 
    }); 
 
} 
 

 
var source = { a: "bbbb", Id: 1, b: { a: "bbb", Id: 2 }, c: "aaa", d: [{ a: "bbbb", Id: 1, b: { a: "bbb", Id: 2 }, c: "aaa" }, { a: "bbbb", Id: 2, b: { a: "bbb", Id: 3 }, c: "aaa" }] }, 
 
    target = { a: "aaa", Id: 1, b: { a: "aaa", Id: 2 }, c: null, d: [{ a: "aaa", Id: 1, b: { a: "aaa", Id: 2 }, c: null }, { a: "aaa", Id: 2, b: { a: "aaa", Id: 3 }, c: null }] }; 
 

 
update(source, target); 
 

 
console.log(target);
.as-console-wrapper { max-height: 100% !important; top: 0; }