【问题标题】:Compare Two Array, if found same key get the value from 2nd Array比较两个数组,如果找到相同的键,则从第二个数组中获取值
【发布时间】:2017-02-13 10:05:30
【问题描述】:

如何比较两个数组,如果找到相同的键,然后从第二个数组中获取值并将其分配给第一个数组。结果是使用第一个数组。例如我有下面的数组:

    var compareit = {
            firstArray : {
                'color': 'blue',
                'width': 400,
                'height': 150,
            },
            secondArray: {
                'color': 'red',
                'height': 500,
            },
    };

目标是,我想要的结果是:{'color': 'red', 'width': '400', 'height': '500'};

非常感谢您的帮助...谢谢 :)

【问题讨论】:

    标签: javascript jquery arrays compare


    【解决方案1】:

    您可以只使用Object.assign() 将值从一个或多个源对象复制到目标对象。

     var compareit = {
       firstArray: {
         'color': 'blue',
         'width': 400,
         'height': 150,
       },
       secondArray: {
         'color': 'red',
         'height': 500,
       },
     };
    
     Object.assign(compareit.firstArray, compareit.secondArray);
     console.log(compareit.firstArray)

    如果您不想操作现有对象compareit.firstArray

    var compareit = {
      firstArray: {
        'color': 'blue',
        'width': 400,
        'height': 150,
      },
      secondArray: {
        'color': 'red',
        'height': 500,
      },
    };
    
    var obj = {};
    Object.assign(obj, compareit.firstArray, compareit.secondArray);
    console.log(obj, compareit)

    【讨论】:

      【解决方案2】:

      您可以遍历第一个数组中的属性,并检查第二个数组中是否存在相同的属性。

      var compareit = {
        firstArray: {
          'color': 'blue',
          'width': 400,
          'height': 150,
        },
        secondArray: {
          'color': 'red',
          'height': 500,
        },
      };
      var result = {};
      for (var key in compareit.firstArray) {
        if (key in compareit.secondArray) {
          result[key] = compareit.secondArray[key];
        } else {
          result[key] = compareit.firstArray[key];
        }
      }
      console.log(result);

      【讨论】:

        【解决方案3】:

        var compareit = {
                    firstArray : {
                        'color': 'blue',
                        'width': 400,
                        'height': 150,
                    },
                    secondArray: {
                        'color': 'red',
                        'height': 500,
                    },
            };
        var result,
            compareObjects=function(comp){
              return Object.assign(comp.firstArray, comp.secondArray);
            };
        
        result=compareObjects(compareit);
        console.log(result);

        【讨论】:

          猜你喜欢
          • 2019-06-12
          • 2023-03-12
          • 2019-06-15
          • 1970-01-01
          • 1970-01-01
          • 2016-02-21
          • 2015-07-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多