gpt4 book ai didi

javascript - 映射到另一个并比较节点

转载 作者:搜寻专家 更新时间:2023-11-01 05:28:34 25 4
gpt4 key购买 nike

我对迭代到 JS 对象和 JavaScript 中的一些数组函数有些怀疑。假设我有这些变量:

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)

最佳答案

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

注意 indexOffiltermapiE9 之前的 iE 中不可用>.

更新:根据@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 的评论回答。

关于javascript - 映射到另一个并比较节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42351677/

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