我想使用基于位置的API在地图项目上放置标记。此API返回一个JSON,其中包含有关GET提供的位置的50个最接近的踏板车的数据。 我想将其中几个JSON的结果合并为一个,将在更大的区域中包含踏板车的所有数据(如果可能的话,不重复)
我已经尝试过connect(ui->button2, SIGNAL(clicked(bool)), ui->button1, SLOT(setChecked(bool)));
,但没有成功,如下面的代码所示。
JSON1.concat(JSON2);
单个API答案如下:
var latitudes = makeArr(48.810067,48.900169,30);
var longitudes = makeArr(2.248876,2.42397,30);
var allskoots= new Array();
for (var i = 0; i < latitudes.length; i++) {
for (var j = 0; j < longitudes.length; j++) {
var req = new XMLHttpRequest();
req.open("GET", "https://api-prod.ibyke.io/v2/boards?latitude="+latitudes[i]+"&longitude="+longitudes[j]);
req.responseType = 'json';
req.send();
req.onload = function() {
var allscoots=allscoots.concat(req.response);
}
}
}
因此,我希望能够从以下两个JSON中获取数据,例如:
{"result":0,
"items":[{"param1":value1_0,
"param2":value2_0},
{"param1":value1_1,
"param2":value2_1}
...
]
}
和
{"result":0,
"items":[{"param1":value1_0,
"param2":value2_0},
{"param1":value1_1,
"param2":value2_1}
]
}
以下结果:
{"result":0,
"items":[{"param1":value1_1,
"param2":value2_1},
{"param1":value1_2,
"param2":value2_2}
]
}
有没有一种简单的方法可以用Javascript完成?
答案 0 :(得分:0)
基本的答案,可以优化,但这是您要寻找的吗?
var r1 = {
"result": 0,
"items": [{
"param1": "value1_0",
"param2": "value2_0"
},
{
"param1": "value1_1",
"param2": "value2_1"
}
]
}
var r2 = {
"result": 0,
"items": [{
"param1": "value1_1",
"param2": "value2_1"
},
{
"param1": "value1_2",
"param2": "value2_2"
}
]
}
var merged = {
"result": 0,
"items": r1.items.concat(r2.items.filter(x => !contains(r1.items, x)))
}
// assuming no duplicates in r2.items
/*
// in case of duplicates
merged.items = r1.items;
for (var i in r2.items) {
if (!contains(merged.items, r2.items[i]))
merged.items.push(r2.items[i]);
}
*/
console.log(merged);
function contains(array, elem) {
for (var i in array) {
if (isEquivalent(array[i], elem)) return true;
}
return false
}
// credit to http://adripofjavascript.com/blog/drips/object-equality-in-javascript.html
function isEquivalent(a, b) {
var aProps = Object.getOwnPropertyNames(a);
var bProps = Object.getOwnPropertyNames(b);
if (aProps.length != bProps.length) {
return false;
}
for (var i = 0; i < aProps.length; i++) {
var propName = aProps[i];
if (a[propName] !== b[propName]) {
return false;
}
}
return true;
}
答案 1 :(得分:0)
解决您的JSON。运行我的脚本。希望你能得到它。
var r1 = {
"result": 0,
"items": [{
"param1": "value1_0",
"param2": "value2_0"
},
{
"param1": "value1_1",
"param2": "value2_1"
}
]
}
var r2 = {
"result": 0,
"items": [{
"param1": "value1_1",
"param2": "value2_1"
},
{
"param1": "value1_2",
"param2": "value2_2"
}
]
}
var final_arr = {"result": 0,"items": []};
final_arr.items.push(r1.items);
final_arr.items.push(r2.items);
console.log(final_arr);