gpt4 book ai didi

javascript - 在 javascript razor 中比较 2 个 json 并合并为 1 个 json

转载 作者:行者123 更新时间:2023-12-02 22:51:20 25 4
gpt4 key购买 nike

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

第一个 json 是从 Controller 获取的。

第二个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);

关于javascript - 在 javascript razor 中比较 2 个 json 并合并为 1 个 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58177203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com