找出不同的值以将部分更新发送到服务器

时间:2018-01-18 16:06:25

标签: ramda.js

从表单提交中我收到两个对象:原始值和脏值。我想弄清楚如何使用以下规则创建发送到服务器的差异:

  1. 应始终包含根对象的id字段
  2. 应包含所有已更改的原始值
  3. 也应包括所有嵌套更改。
  4. 如果id以外的嵌套值发生更改,则还应包含id。
  5. 原始值:

    { 
        "id":10,
        "name": "tkvw"
        "locale": "nl",
        "address":{
            "id":2,
            "street": "Somewhere",
            "zipcode": "8965",
        },
        "subscriptions":[8,9,10],
        "category":{
           "id":6
        },    
    }
    

    预期的差异对象示例:

    1)用户将字段name更改为“Foo”

    {
        "id":10,
        "name":"foo"
    }
    

    2)用户更改地址节点上的字段streetcategory

    {
        "id":10,
        "address":{
            "id": 2,
            "street":"Changed"
        },
        "category":{
            "id":5
        }
    }
    

    我确实理解函数式编程的基础知识,但我只需要一个正确方向的提示(可能是一些元代码)。

1 个答案:

答案 0 :(得分:0)

查看JSON Patch (rfc6902),JSON Patch是一种描述JSON文档更改的格式。例如:

[
  { "op": "replace", "path": "/baz", "value": "boo" },
  { "op": "add", "path": "/hello", "value": ["world"] },
  { "op": "remove", "path": "/foo"}
]

通过与JS对象/数组进行比较生成补丁,然后可以将补丁应用于原始对象(例如,在服务器端)以反映更改。

您可以使用fast-json-patch库创建补丁。

const obj1 = {"id":10,"name":"tkvw","locale":"nl","address":{"id":2,"street":"Somewhere","zipcode":"8965"},"subscriptions":[8,9,10],"category":{"id":6}};

const obj2 = {"id":10,"name":"cats","locale":"nl","address":{"id":2,"street":"Somewhere","zipcode":"8965"},"subscriptions":[8,9,10,11],"category":{"id":7}};

const delta = jsonpatch.compare(obj1, obj2);

console.log('delta:\n', delta);

const doc = jsonpatch.applyPatch(obj1, delta).newDocument;

console.log('patched obj1:\n', doc);
<script src="https://cdnjs.cloudflare.com/ajax/libs/fast-json-patch/2.0.6/fast-json-patch.min.js"></script>