5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

JavaScriptのオブジェクト比較をできるだけ短いコードで行う

Posted at

はじめに

Reactを書いていて、initialState(初期ステート)とstate(現在のステート)の比較を行いたいことがあった。
しかし、意外とJavaScriptではオブジェクトの比較が難しかったので、できるだけ短いヘルパー関数を作ったので共有したい。

結論

helper.js
/* オブジェクトをソート済み配列に変換する */
const objToSortedArray = obj => Object.entries(obj).sort()

/* ソート済み配列を文字列に変換して比較する */
const isEqualOneDimentionalArray = (obj1, obj2) =>
  JSON.stringify(objToSortedArray(obj1)) === JSON.stringify(objToSortedArray(obj2))

/* 再帰処理を行い、ネストされたオブジェクトまで比較する */
export const isEqual = (obj1, obj2) => isEqualOneDimentionalArray(obj1, obj2)
  && objToSortedArray(obj1).map(([key, val]) => typeof val === "object" ? isEqual(val, obj2[key]) : true)
howToUse.js
import {isEqual} from "./helper.js"

const initialState = {
  tmpConditions: {
    target: "makeup",
    personalColor: false,
    faceType: false,
    items: []
  }
}

const state = {
  tmpConditions: {
    target: "makeup",
    personalColor: true,
    faceType: false,
    items: [1, 23]
  }
}

console.log(isEqual(initialState, state)) // false

5
1
0

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
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?