我想问一下我如何比较这两个json并将它们合并到javascript中?

第一个json是从控制器获取的。

第二个json是在我输入之后。

任何帮助表示赞赏。

第一个json

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


第二个json

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


预期产量

[{"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"
    }]

最佳答案

这可能对您有帮助!



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);

09-18 03:00