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

More than 1 year has passed since last update.

jsの連想配列の順番が勝手に変わる

Last updated at Posted at 2022-09-01

連想配列の順番が変わる

開発している時に連想配列の順番が勝手に変わることに気が付き、どういった場合に変わってしまうのかをまとめていきます。
結論として、jsではオブジェクトの並び順は保証されていないので、並び順を保持したい場合は配列で管理する必要があります。

以下の結果はchromeで流した結果です。

要素の追加

let aa = {2: 2, 6: 6}
aa[3] = 3
aa["a"] = "a"
console.log("要素の追加", aa)
// => 要素の追加 {2: 2, 3: 3, 6: 6, a: 'a'}

valuesまたはkeysを取得

let bb = {3: 3, 5: 5, 1: 1}
console.log("bb", bb)
console.log('bbのvaluesを取得', Object.values(bb))
console.log('bbのkeysを取得', Object.keys(bb))
// => bb {1: 1, 3: 3, 5: 5}
// => bbのvaluesを取得 [1, 3, 5]
// => bbのkeysを取得 ['1', '3', '5']

連想配列の結合

aa = {2: 2, 6: 6}
bb = {3: 3, 5: 5, 1: 1}
console.log('結合', Object.assign(aa, bb))
// => 結合 {1: 1, 2: 2, 3: 3, 5: 5, 6: 6}

要素の削除

bb = {3: 3, 5: 5, 1: 1}
delete bb[5]
console.log("要素の削除", bb)
// => 要素の削除 {1: 1, 3: 3}
1
0
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
1
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?