1
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 5 years have passed since last update.

二階以上の層のjsonに値を追加したい

1
Posted at

死ぬほど詰まったので、書いた。

2階層以上のJSON

json.js
var data = {
	"A" : {
		"0" : {
			"name" : "hoge",
			"foo" : "bar"
		}
	},
	"B" : {
		"0" : {
			"name" : "aaa",
			"foo" : "bar"
		}
	},
	"C" : {
		"0" : {
			"name" : "bbb",
			"foo" : "bar"
		},
		"1" : {
			"name" : "here",
			"foo" : "bar"
		}
	}
}

ここに新しく値を追加したい。

json2.js
var newdata = {
	"name" : "yeah",
	"foo" : "bar"
}

仕組みは楽だが、objectの処理がだるい

仕組みは割と簡単。
AかBかCかのキーを取って、長さを取得して、最後にデータを突っ込んでやればいい。

ただ、オブジェクトだと配列みたいに上手くいかない。

var length = Object.keys(data["C"]).length;
data["C"][length] = newdata;

foreach回すにも、Object.keysを使う

Object.keys(data).forEach(function(k){
	Object.keys(data[k]).forEach(function(v){
		if(newdata.name == data[k][v]){
			console.log("hello");
		});
	});
});

なんかあまり綺麗じゃ無さそう。もっといい方法があると信じてる。

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