2个键值对象js之间的数学差异

时间:2019-03-20 15:26:46

标签: javascript arrays object key

如果我有2个这样的对象:

var obj1 = {'a': [2, 3, 4], 'b': [5, 5, 5]}
var obj2 = {'a': [1, 1, 1], 'b': [2, 2, 2]}

我如何获得这样的第三个对象:

obj3 = {'a': [1, 2, 3], 'b': [3, 3, 3]} // difference between obj1 and obj2

我尝试过,但没有结果:

var obj1 = {'a': [2, 3, 4], 'b': [5, 5, 5]}
var obj2 = {'a': [1, 1, 1], 'b': [2, 2, 2]}
var obj3 = Object.keys(obj1).filter(k => obj1[k] - obj2[k]);
console.log(obj3)

6 个答案:

答案 0 :(得分:4)

您可以使用 Object.keys() .forEach() 方法调用来迭代keys并进行所需的计算。< / p>

这应该是您的代码:

var res = {};
Object.keys(obj1).forEach(function(k){
   res[k] = obj1[k].map((v,i) => v - obj2[k][i]);
});

演示:

var obj1 = {'a': [2, 3, 4], 'b': [5, 5, 5]}
var obj2 = {'a': [1, 1, 1], 'b': [2, 2, 2]}
var res = {};
Object.keys(obj1).forEach(function(k){
   res[k] = obj1[k].map((v,i) => v - obj2[k][i]);
});

console.log(res);

答案 1 :(得分:3)

使用reduce和map的示例。

编辑:我记录了一些步骤来帮助您了解正在发生的事情。

/**
 * Returns the difference between each value in an array
 * positioned at each key listed in keys between objA and objB.
 *
 * @param {Object} objA - Every key should container an array of numbers to diff.
 * @param {Object} objB - Should match structure with objA.
 * @param {string[]} [keys] - Optional array with keys to diff, by default uses all the keys.
 * @returns {Object} - Object matching objA structure with diff'ed values in each key.
 */ 
function keyDiff(objA, objB, keys=Object.keys(objA)) {

  // Array.reduce "reduces" an array to a single object using using a function.
  // Function receives 2 arguments:
  // - Accumelated value (val, result of previous steps in every iteration).
  // - Current iterated value of array (key).
  return keys.reduce(function(acc, key) {
    
    // Array.map "maps" one array to another using a function.
    // Function receives 2 arguments:
    // - Current iterated value of array (v).
    // - Current iterator index (index).
    //
    // Current reducer value "key" is used to map objA values for key to
    // differnce with objB. This is done at the position specied by map index.
    // The result is set to the accumulater "acc" object which gets returned
    // at the end of the reducer.
    acc[key] = objA[key].map(function(v, index) {
      // Subtract objB value from objA value
      return v - objB[key][index];
    })
  
    // Return the new accumelator "acc" value.
    // The returned value of each step in the reducer is accumulator "acc".
    // This is the first value in the function passed as argument in the reducer.
    return acc;

  // By Default "null" is the inital accumulator value.
  // Since we need an object to start with we specify "{}" as the inital value.
  }, {});
}

var obj1 = {'a': [2, 3, 4], 'b': [5, 5, 5]}
var obj2 = {'a': [1, 1, 1], 'b': [2, 2, 2]}

var obj3 = keyDiff(obj1, obj2);
console.log(obj3);

答案 2 :(得分:2)

这是我可以创建的最简单的版本。

const obj1 = { 'a': [2, 3, 4],'b': [5, 5, 5]};
const obj2 = { 'a': [1, 1, 1],'b': [2, 2, 2]};
let   obj3 = {};

for (k in obj1) {
   obj3[k] = obj1[k].map((v, i) => v - obj2[k][i])
};
console.log(obj3)

答案 3 :(得分:2)

您可以采用适用于任何深度对象的迭代和递归方法。

function delta(a, b) {
    return typeof a === 'object'
        ? Object.assign(
            Array.isArray(a) ? [] : {},
            ...Object.keys(a).map(k => ({ [k]: delta(a[k], b[k]) }))
        )
        : a - b;
}

var obj1 = { a: [2, 3, 4], b: [5, 5, 5] },
    obj2 = { a: [1, 1, 1], b: [2, 2, 2] },
    result = delta(obj1, obj2);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 4 :(得分:1)

怎么样

var obj1 = {'a': [2, 3, 4], 'b': [5, 5, 5]}
var obj2 = {'a': [1, 1, 1], 'b': [2, 2, 2]}

var resultObj = {};

for(var i in obj1) {
  var firstObjArray = obj1[i];
  var secondObjArray = obj2[i];
  var differenceArray = firstObjArray.map(function(a, index) {
    return firstObjArray[index] - secondObjArray[index]
  });
  resultObj[i] = differenceArray;
}

console.log(resultObj)

答案 5 :(得分:1)

您可以使用Array.map()创建可重用的数组减法函数。

此后,只需简单地遍历对象键并在匹配的键上执行该功能即可。

def printDataFrame(df):
    for i in range(len(df.index)):
        row = list(df.iloc[i])
        print("\t".join(map(str, row)))


printDataFrame(df)