我对在JavaScript中迭代JS对象和一些数组函数有些怀疑。假设我有这些变量:
var json1 = "[{"id": 1, "name":"x"}, {"id": 2, "name":"y"}]";
var json2 = "[{"id": 1, "name":"x"}, {"id": 2, "name":"y"}, {"id": 3, "name":"z"}]";
如何只使用数组中的ID
创建变量var ids1 = json1.ids (would be 1,2)
var ids2 = json2.ids (would be 1,2,3)
并仅使用不同的ID
创建另一个变量var idsdiff = diff(ids1, ids2) (would be 3)
答案 0 :(得分:2)
您可以为id
使用哈希表,并使其与值有所不同。然后通过过滤来渲染结果。
function getId(a) { return a.id; }
var obj1 = JSON.parse('[{"id": 1, "name":"x"}, {"id": 2, "name":"y"}]');
var obj2 = JSON.parse('[{"id": 1, "name":"x"}, {"id": 2, "name":"y"}, {"id": 3, "name":"z"}]');
var ids1 = obj1.map(getId);
var ids2 = obj2.map(getId);
var hash = {};
ids1.forEach(function (a) {
hash[a] = 1;
});
ids2.forEach(function (a) {
hash[a] = (hash[a] || 0) - 1;
});
var difference = Object.keys(hash).filter(function (a) { return hash[a]; }).map(Number);
console.log(ids1);
console.log(ids2);
console.log(hash);
console.log(difference);
.as-console-wrapper { max-height: 100% !important; top: 0; }
使用lodash,您可以使用_.xor
来获得对称差异。
var ids1 = [1, 2],
ids2 = [1, 2, 3];
console.log(_.xor(ids1, ids2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
答案 1 :(得分:2)
var json1 = [{"id":1,"name":"x"}, {"id":2,"name":"y"}],
json2 = [{"id":1,"name":"x"}, {"id":2,"name":"y"}, {"id":3,"name":"z"}],
result1 = json1.map(function (a) { return a.id; }),
result2 = json2.map(function (a) { return a.id; });
var diffs = result2.filter(function (item) {
return result1.indexOf(item) < 0;
});
console.log(result1);
console.log(result2);
console.log(diffs);
在indexOf
之前,filter
内无法提供map
和iE
以及iE9
。
更新:根据@ alexandru-Ionutmihai的评论,过滤器将在[1,2,4]
和[1,2,3]
上失败
此代码似乎更好:
var json1 = [{"id":1,"name":"x"}, {"id":2,"name":"y"}],
json2 = [{"id":1,"name":"x"}, {"id":2,"name":"y"}, {"id":3,"name":"z"}],
result1 = json1.map(function (a) { return a.id; }),
result2 = json2.map(function (a) { return a.id; });
//as per @alexandru-Ionutmihai this is inaccurate for [1,2,4] and [1,2,3]
/*var diffs = result2.filter(function (item) {
return result1.indexOf(item) < 0;
});*/
//here's a workaround
function arr_diff(a, b) {
var i,
la = a.length,
lb = b.length,
res = [];
if (!la)
return b;
else if (!lb)
return a;
for (i = 0; i < la; i++) {
if (b.indexOf(a[i]) === -1)
res.push(a[i]);
}
for (i = 0; i < lb; i++) {
if (a.indexOf(b[i]) === -1) res.push(b[i]);
}
return res;
}
var diffs = arr_diff(result1, result2),
testDiff = arr_diff([1, 2, 4], [1, 2, 3]);
console.log(result1);
console.log(result2);
console.log(diffs);
console.log(testDiff);
arr_diff
感谢@ Nomaed对此question's答案的评论。
答案 2 :(得分:1)
您可以将map
方法与filter
方法结合使用。
var json1 = [{"id": 1, "name":"x"}, {"id": 2, "name":"y"}];
var json2 = [{"id": 1, "name":"x"}, {"id": 2, "name":"y"}, {"id": 3, "name":"z"}];
var j1=json1.map((x)=>{return x.id});
var j2=json2.map((x)=>{return x.id});
var diff = j2.filter(function(el){
return j1.indexOf(el)==-1;
}).concat(j1.filter(function(el){
return j2.indexOf(el)==-1;
}));
console.log(diff);
&#13;
此外,如果两个json数组都包含不同的IDs
,则此代码有效。
var json1 = [{"id": 1, "name":"x"}, {"id": 2, "name":"y"}, {"id": 4, "name":"y"}, {"id": 5, "name":"y"}];
var json2 = [{"id": 1, "name":"x"}, {"id": 2, "name":"y"}, {"id": 3, "name":"z"}];
var j1=json1.map((x)=>{return x.id});
var j2=json2.map((x)=>{return x.id});
var diff = j2.filter(function(el){
return j1.indexOf(el)==-1;
}).concat(j1.filter(function(el){
return j2.indexOf(el)==-1;
}));
console.log(diff);
&#13;
答案 3 :(得分:1)
如果未解析那些JSONs
,则需要额外执行一步:
json1 = JSON.parse(json1);
如果没有,请使用此代码:
var json1 = [{"id": 1, "name":"x"}, {"id": 2, "name":"y"}];
var json2 = [{"id": 1, "name":"x"}, {"id": 2, "name":"y"}, {"id": 3, "name":"z"}];
// extra steps, if necessary
// json1 = JSON.parse(json1);
// json2 = JSON.parse(json2);
function returnID (item) {
return item.id;
};
json1 = json1.map(returnID);
json2 = json2.map(returnID);
var diff = json2.filter(function (item) {
return json1.indexOf(item) < 0;
});
console.log(diff);
&#13;
答案 4 :(得分:0)
要使数组只填充每个对象的var ws = new WebSocket('ws://localhost:8181/');
var hasConnected = false;
function startWebSockets() {
ws.onmessage = function (messageEvent) {
onReceiveMessage(messageEvent.data);
};
ws.onopen = function () {
onConnectionOpened();
};
ws.onclose = function () {
onConnectionClosed();
}
}
function onReceiveMessage(messageData) {
var messageParts = messageData.includes('\\') ? messageData.split('\\') : messageData;
if (messageData.includes("\\")) {
if (messageParts[0] == "compose:show_custom_notification") {
showBootstrapNotification(messageParts[1], messageParts[2], messageParts[3], messageParts[4]);
}
}
else {
if (messageData == "compose:authentication_complete") {
console.log('Authentication to WebSocket server has been completed.');
}
if (messageData == "compose:authentication_failed") {
sendMessage("client_identity_token " + habboSso);
}
}
}
function onConnectionOpened() {
console.log('Connected to the WebSocket server.');
hasConnected = true;
sendMessage("client_identity_token " + habboSso);
}
function onConnectionClosed() {
if (!hasConnected) {
console.log('Failed to connect to the WebSocket server.');
}
else {
console.log('Your connection to the WebSocket server was unexpectedly closed.');
}
}
function sendMessage(message) {
if (hasConnected) {
ws.send(message);
}
}
startWebSockets();
function showBootstrapNotification(notificationTitle, notificationContent, notificationColor, notificationSize) {
console.log('trying to execute notification');
var notificationArea = $('#notification_area');
var notificationHtml;
const randomId = '' + new Date().getTime() + '_' + Math.random();
notificationHtml += '<div class="col-md-' + notificationSize + ' col-centered">';
notificationHtml += '<div id="' + randomId + '" class="draggable panel panel-pink">';
notificationHtml += '<div class="panel-heading" style="background-color: ' + notificationColor + '">';
notificationHtml += notificationTitle;
notificationHtml += '</div>';
notificationHtml += '<div class="panel-body">';
notificationHtml += notificationContent;
notificationHtml += '</div>';
notificationHtml += '</div>';
notificationHtml += '</div>';
$("#notification_area").prepend(notificationHtml);
setTimeout(function() {
const myToBeDraggableDiv = $('#'+randomId);
myToBeDraggableDiv.removeAttr('id');
myToBeDraggableDiv.draggable();
}, 0);
}
属性,请执行简单操作...
id
如果您使用的是ES6或版本转换程序,则可以使用扩展运算符来区分两者:
var ids1 = json1.map(x => x.id)
var ids2 = json2.map(x => x.id)
var diff = [...id1.filter(x => id2.indexOf(x) == -1), ...id2.filter(x => id1.indexOf(x) == -1)]
&#13;
答案 5 :(得分:0)
在这里,我让你有两个函数来获得你想要的结果:
第一个函数(getIds):
var json1 = [{"id": 1, "name":"x"}, {"id": 2, "name":"y"}];
var json2 = [{"id": 1, "name":"x"}, {"id": 2, "name":"y"}, {"id": 3, "name":"z"}];
function getIds (array) {
return array.map(function (obj) {
return obj.id;
});
}
console.log(getIds(json1));
console.log(getIds(json2));
第二个功能(getDiff)
var json1 = [1, 2, 4, 5];
var json2 = [1, 2, 3];
function getDiff (array1, array2) {
return array1.concat(array2).filter(function (id, index, arr) {
return arr.indexOf(id) === arr.lastIndexOf(id);
});
}
console.log(getDiff(json1, json2));