簡體   English   中英

如何使用_lodash處理數組中的字段以備份並還原它們?

[英]How can I use _lodash to work on fields inside an array backing them up and restoring them?

我需要做一些數組操作,並希望有人告訴我_lodash是否可以用於此目的。 我所擁有的是一個名為result的數組,其中包含以下內容:

var result = 
[
{"referenceId":20,"callerId":1, "location":2},
{"referenceId":21,"callerId":1, "location":3}
]

我想為這個數組創建一個備份,如下所示:

var resultBackup =
[
{"location":2},
{"location":3}
]

我的用戶可能會更改數據,以使數組如下所示:

var result = 
[
{"referenceId":20,"callerId":1, "location":999},
{"referenceId":21,"callerId":1, "location":123}
]

我需要能夠僅使用備份陣列中數據中的location字段來更新我的原始陣列,並將其還原到:

var result = 
[
{"referenceId":20,"callerId":1, "location":2},
{"referenceId":21,"callerId":1, "location":3}
]

_lodash是否可能發生這種情況?

要創建備份陣列,可以使用_.map或本機Array.prototype.map將原始對象轉換為僅具有一個屬性的新對象:

var resultBackup = _.map(result, function(e) { // or result.map(function(e) {
    return {location: e.location};
});

然后,要還原值,您想將結果對象與備份對象“合並”。 Lo-Dash _.assign提供_.assign

_.forEach(result, function(e, index) {
    _.assign(e, resultBackup[index]);
});

或沒有圖書館:

result.forEach(function(e, index) {
    var backup = resultBackup[index];
    for (var prop in backup) {
        e[prop] = backup[prop];
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM