简体   繁体   中英

Comparing 2 json and merge to 1 json in javascript razor

I would like to ask that how can i comparing these two json and merge them into one in javascript?

First json is get from controller.

Second json is after i input.

Any help is appreciated.

First json

[{"name":"Stock",
    "data":
    [{"name":"Fish", 
      "amount":80,
      "color":"#0000ff"
     },
     {"name":"Meat", 
     "amount":20,
     "color":"#fd0000"
     }]
    }]

2nd json

[{"name":"Stock",
    "data":
    [{"name":"Fish", 
      "amount":5,
      "color":"#008000"
     },
     {"name":"Meat", 
     "amount":10,
     "color":"#00FF00"
     }]
    }]

Expected Output

[{"name":"Stock",
   "data":
   [{"name":"Fish", 
     "amount":80,  // first json amount
     "color":"#0000ff"
    },
    {"name":"Meat", 
     "amount":20,  // first json amount
     "color":"#fd0000"
    },
    {"name":"Fish", 
     "amount":75, // 80 - 5 = 75 (first json - 2nd json)
     "color":"#008000"
    },
    {"name":"Meat", 
     "amount":10, // 20 - 10 = 10 (first json - 2nd json)
     "color":"#00FF00"
    }]

This might help you!!

 let json1 = [{"name":"Stock", "data": [{"name":"Fish", "amount":80, "color":"#0000ff" }, {"name":"Meat", "amount":20, "color":"#fd0000" }] }] let json2 = [{"name":"Stock", "data": [{"name":"Fish", "amount":5, "color":"#008000" }, {"name":"Meat", "amount":10, "color":"#00FF00" }] }] let amountMap = {}; let stockMap = {}; let result = []; function addToResult(jsonA){ jsonA.forEach((stock)=>{ if( stockMap[stock.name]==undefined ){ stockMap[stock.name] = stock; result.push(stockMap[stock.name]); } stock.data.forEach((data)=>{ if( amountMap[stock.name+";"+data.name]==undefined ){ amountMap[stock.name+";"+data.name] = data.amount; // no need to push as data already present there }else{ amountMap[stock.name+";"+data.name] = amountMap[stock.name+";"+data.name] - data.amount; data.amount = amountMap[stock.name+";"+data.name]; //replace amount stockMap[stock.name].data.push(data); } }); }); } addToResult(json1); addToResult(json2); console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM