【问题标题】:Map into another and compare node映射到另一个并比较节点
【发布时间】:2017-07-10 03:39:21
【问题描述】:

我对迭代到 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)

【问题讨论】:

标签: javascript arrays json


【解决方案1】:

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

注意indexOffiltermapiE 之前的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 答案的评论。

【讨论】:

  • 正如@alexandru-Ionutmihai 所说,如果您使用json1 = [1,2,3]json2 = [1,2,4] 等数组,则此方法不起作用
【解决方案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));
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"&gt;&lt;/script&gt;

【讨论】:

    【解决方案3】:

    如果那些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);

    【讨论】:

    • 如果json1=[1,2,4]json2=[1,2,3] 这个代码将不起作用。
    【解决方案4】:

    您可以将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);

    此外,如果两个 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);

    【讨论】:

      【解决方案5】:

      要让数组只填充每个对象的 id 属性,只需...

      var ids1 = json1.map(x => x.id)
      var ids2 = json2.map(x => x.id)
      

      如果你使用的是 ES6,或者是版本转译器,你可以使用扩展运算符来获取两者之间的区别,例如:

      var diff = [...id1.filter(x => id2.indexOf(x) == -1), ...id2.filter(x => id1.indexOf(x) == -1)]
      

      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 ids1 = json1.map(x => x.id);
      var ids2 = json2.map(x => x.id);
      
      var diff = [...ids1.filter(x => ids2.indexOf(x) == -1), ...ids2.filter(x => ids1.indexOf(x) == -1)];
      console.log(diff);

      【讨论】:

        【解决方案6】:

        这里我让你用两个函数来得到你想要的结果:

        第一个函数(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));

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-11-16
          • 1970-01-01
          • 1970-01-01
          • 2014-11-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多