假设我有两个JSON字符串:
json1 = [{"hc-key":"ar-tf","value":221},{"hc-key":"ar-ba","value":10820},{"hc-key":"ar-sj","value":230}]
json2 = [{"hc-key":"ar-ba","value":2890151},{"hc-key":"ar-sj","value":15625084},{"hc-key":"ar-tf","value":367828}]
我想要做的是通过“hc-key”将它们加入到新的JSON字符串中,其中新的“value”是结果将json1中的值除以json2中的值。在JavaScript中。
请注意,json2中的数据与json1中的数据顺序不同,但它们都具有完全相同的键。
生成的JSON应为:
result = [{"hc-key":"ar-ba","value":10820/2890151},{"hc-key":"ar-sj","value":230/15625084},{"hc-key":"ar-tf","value":221/367828}]
(我已经忽略了产生的澄清值)
感谢。
答案 0 :(得分:3)
罗伯特是正确的,连接是更好的服务器端,但你想要做的只是使用一些JavaScript循环。
我没有为此示例中的错误处理而烦恼,但我还建议您在分割之前确认您有实数并且您没有除以零。
var json1 = [
{"hc-key":"ar-tf","value":221},
{"hc-key":"ar-ba","value":10820},
{"hc-key":"ar-sj","value":230}];
var json2 = [
{"hc-key":"ar-ba","value":2890151},
{"hc-key":"ar-sj","value":15625084},
{"hc-key":"ar-tf","value":367828}];
var result = [];
for(var i = 0; i < json1.length; i++)
{
var key = json1[i]['hc-key'];
for(var j = 0; j < json2.length; j++) {
if(json2[j]['hc-key'] == key) {
result.push({
"hc-key":key,
"value": json1[i]['value'] / json2[j]['value']
});
break;
}
}
}
//show results
var key, value;
var $results = $('.results tbody');
for(var i = 0; i < result.length; i++)
{
key = result[i]['hc-key'];
value = result[i]['value'];
$results.append('<tr><td>' + key + '</td><td>' + value + '</td></tr>');
}
td {
padding-right: 15px;
text-align: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<b>results:<b>
<table class="results">
<tbody></tbody>
</table>
答案 1 :(得分:1)
这是一种功能性的方法。这种方式也适用于异步编程的ReactiveX observable。
Array.prototype.concatAll = function() {
var results = [];
this.forEach(function(subArray) {
results.push.apply(results, subArray);
});
return results;
};
result = json1.map(function(obj1) {
return json2.
filter(function(obj2) {return obj2["hc-key"] == obj1["hc-key"]}).
map(function(obj2) {
return {
"hc-key": obj1["hc-key"],
"value": obj1.value / obj2.value
};
});
}).concatAll()