【问题标题】:Comparison of JSON arrays Angular 6JSON数组Angular 6的比较
【发布时间】:2019-08-01 03:07:03
【问题描述】:

我有两个不同的 JSON 对象:

a = [{id:"1",time:"timestamp"},{id:"2",time:"timestamp"},{id:"3",time:"timestamp"},{id:"4",time:"timestamp"},{id:"5",time:"timestamp"}];
b = [{id:"1",time:"timestamp"},{id:"3",time:"timestamp"},{id:"4",time:"timestamp"}];

我想根据数组 a 的匹配创建一个新数组。例如,上面示例中的输出如下所示:

c = ["1","0","1","1","0"]

其中 1 是我们找到 id 的情况,而 0 是我们没有得到 id 的情况。

到目前为止我试过这个:

c = [];

var val = JSON.parse(b);
if (val.length > 0) {
  val.forEach((obj) => {
    var match = a.find(({
      id
    }) => obj.id === id);
    if (!match) {
      c.push("0");
    } else {
      c.push("1");
    }
  });
}
console.log(c);

谁能告诉我我在这方面做错了什么。

谢谢

【问题讨论】:

  • 输出什么?

标签: arrays json angular


【解决方案1】:

据我了解,您应该反过来做。如果要检查第一个列表的值是否在第二个列表中,则需要循环第一个列表而不是第二个列表。

c = [];

    var val = JSON.parse(a);
    if( val.length > 0 ) {
       val.forEach((obj)=>{
         var match = b.find(({id}) => obj.id === id);
         if(!match){
           c.push("0");
         }
         else {
           c.push("1");
         }
       });
    }
    console.log(c);

【讨论】:

  • 是的,我现在看到了问题,谢谢@ukn
【解决方案2】:

您需要将forEacha 一起使用,然后在b 中找到一个元素。

var a = [{id:"1",time:"timestamp"},{id:"2",time:"timestamp"},{id:"3",time:"timestamp"},{id:"4",time:"timestamp"},{id:"5",time:"timestamp"}];
var b = [{id:"1",time:"timestamp"},{id:"3",time:"timestamp"},{id:"4",time:"timestamp"}];

var c = [];
var val = a;

if (val.length > 0) {
  val.forEach((obj) => {
    var match = b.find(({
      id
    }) => obj.id === id);
    if (!match) {
      c.push("0");
    } else {
      c.push("1");
    }
  });
}
console.log(c);

【讨论】:

  • 这很完美,我想这是最好的方法。谢谢@zmag
【解决方案3】:

使用简单的For 循环;

 a = [{id:"1",time:"timestamp"},{id:"2",time:"timestamp"},{id:"3",time:"timestamp"},{id:"4",time:"timestamp"},{id:"5",time:"timestamp"}];
    b = [{id:"1",time:"timestamp"},{id:"3",time:"timestamp"},{id:"4",time:"timestamp"}];

    var arr  = [];
    var a_keys =  a.map(e => e.id);
    var b_keys =  b.map(e => e.id);
    
    for(var i=0;i<a_keys.length;i++){
        if(b_keys.indexOf(a_keys[i]) != -1){
           arr.push('1');
       }else{
       arr.push('0');
       }
    }

    console.log(arr);

a = [{id:"1",time:"timestamp"},{id:"2",time:"timestamp"},{id:"3",time:"timestamp"},{id:"4",time:"timestamp"},{id:"5",time:"timestamp"}];
    b = [{id:"1",time:"timestamp"},{id:"3",time:"timestamp"},{id:"4",time:"timestamp"}];

    var arr  = [];

    
    for(var i= 0; i < a.length; i++) {
        for(var j= 0; j < b.length; j++) {
         if(a[i].id ===  b[j].id){
          arr.push('1');
          break;
         }
         if((a[i].id !==  b[j].id) && (j === (b.length - 1))){
             arr.push('0');
         }
       }
     }

    console.log(arr);

【讨论】:

  • 这会增加复杂性@Mahi,更好的方法是不要以这种方式迭代更大的数组。
猜你喜欢
  • 1970-01-01
  • 2019-06-08
  • 1970-01-01
  • 1970-01-01
  • 2013-04-29
  • 1970-01-01
  • 2019-07-29
  • 2019-07-12
  • 2019-05-28
相关资源
最近更新 更多