如何有条件地检查对象值是否已设置或等于smth和跟踪更改?

时间:2019-01-16 22:17:22

标签: javascript node.js

我不知道如何使这段代码更短,我还需要检查和跟踪更改的其他值,因此代码变得又大又复杂

doc.name = doc.name === offer.title
  ? doc.name
  : () => {
      shouldUpdate = true ;
      return offer.title
  };

doc.uri = doc.uri
  ? doc.uri
  : () => {
    shouldUpdate = true;
    return encodeURI(offer.title)
  };

doc.info = doc.info
  ? doc.info
  : () => {
    shouldUpdate = true;
    return {
      activation: offer.activation,
      image: offer.image
    };
  };

4 个答案:

答案 0 :(得分:0)

对于doc.uridoc.info m,您可以使用它本身的值或函数。

doc.uri = doc.uri
    || () => {
        shouldUpdate = true;
        return encodeURI(offer.title)
    };

doc.info = doc.info
    || () => {
        shouldUpdate = true;
        return {
            activation: offer.activation,
            image: offer.image
        };
    };

答案 1 :(得分:0)

您可以使用Short-circuit operatorsdoc.uridoc.info的分配转换为:

doc.uri = doc.uri || () => {shouldUpdate = true; return encodeURI(offer.title)};
doc.info = doc.info || () => {shouldUpdate = true; return {
    activation: offer.activation,
    image: offer.image
}};

答案 2 :(得分:0)

此函数将比较相同类型的两个对象中的所有属性。 在函数takeAction中,它将采取适当的措施。可能可以做得更好,但我发现它更具可读性。

let a = { name : 'same', uri: 'samee', info: 'not same'};
const b = { name : 'same', uri: 'samee', info: 'same'};
areSame(a,b);
console.log(a, b);

function areSame(a,b){
  const aKeys = Object.keys(a);
  for(let key of aKeys){
    if(a[key] !== b[key]){
      // shouldUpdate = true;
      takeAction(a,b, key)
    } 
  }
}

function takeAction(a,b, key){
  switch(key){
    case "name": {
      a.name = b.name;
      document.write('name action taken');
      break;
    }
    case "uri": {
      // parse uri
      a.uri = b.uri;
      document.write('uri action taken');
      break;
    }
      
    case "info": {
        // activation: offer.activation,
        // image: offer.image
      document.write('info action taken');
      break;
    }
  }
}

答案 3 :(得分:0)

您甚至可以使它变得更糟并使用逗号!

doc.name = doc.name === offer.title ? doc.name : (shouldUpdate = true, offer.title);
doc.uri = doc.uri || (shouldUpdate = true, encodeURI(offer.title));
doc.info = doc.info || (shouldUpdate = true, {
      activation: offer.activation,
      image: offer.image
});