0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

TypeScriptでJSON or 配列データ差異チェックを再帰的にやりたい

Last updated at Posted at 2024-11-21

やりたいこと

JSON or 配列データの更新リクエストがきたとき、前回と差異があるのかを判定したい。
差異がなければDB更新処理をやらない。(負荷軽減)

[main.ts]

// JSONオブジェクト,配列の差分を比較する
function is_difference_data(source: any, target: any) {

  if (source instanceof Object) {
    if (!(target instanceof Object)) {
      return true;
    }
  }

  // arrayは並び順を併せる
  if (Array.isArray(source)) {
    if (!(Array.isArray(target))) {
      return true;
    }
      source.sort();
      target.sort();
  }

  for (const key in source) {
    const s_value = Object(source)[key];
    // targetにkeyが存在しない場合は差分があると判断
    if (!(key in target)) {
      return true;
    }
    const t_value = Object(target)[key];

    if (Array.isArray(s_value) || s_value instanceof Object) {
      // 再帰的に差分を比較
      if (is_difference_data(s_value, t_value)) {
        return true;
      }
      // 文字列、数値、真偽値の場合は比較
    } else {
      if (s_value != t_value) {
        return true;
      }
    }
  }
  return false;
}


// 動作確認
function test_is_difference_data() {

  // 差分無し
  const source = {
    id: 1,
    name: {
      firstname: "taro",
      lastname: "kimura",
    },
    address: ["address1", "address2"],
  };
  const target = {
    id: 1,
    name: {
      firstname: "taro",
      lastname: "kimura",
    },
    address: ["address2", "address1"],
  };
  const res1 = is_difference_data(source, target);
  console.log(res1); // false

  // 差分あり
  const source2 = {
    id: 1,
    name: {
      firstname: "taro",
      lastname: "kimura",
    },
    address: ["address1"],
  };
  const target2 = {
    id: 1,
    name: {
      firstname: "taro diff",
      lastname: "kimura",
    },
    address: ["address1"],
  };
  const res2 = is_difference_data(source2, target2);
  console.log(res2); // true

}

test_is_difference_data()

実行コマンド

node_modules/.bin/ts-node main.ts
0
0
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?