Iterate through nested objects


#1

Hi, I have some nested objects and I want to print their properties. Here’s my code:

main.x1y1.name = "x1y1";
main.x1y1.piece = "";
main.x1y1._textField = mc.txt_x1y1;
main.x1y1.x = 0;
main.x1y1.y = 0;

main.x2y1.name = "x2y1";
main.x2y1.piece = "";
main.x2y1._textField = mc.txt_x2y1;
main.x2y1.x = 0;
main.x2y1.y = 0;
...

How can I trace piece or name properties of objects?


#2

you might want to take a look at the new methods that have been introduced in ES6 such as Objet.keys(), which will list the keys in objects, Object.values(), which will list the values, and Object.entries() which will list the key,values in individual arrays: For example, I modified what you had here by making the mc.txt_x1y1 to just “txt_x1y1” to give:

var main = {
	x1y1: {
		name: "x1y1",
		piece: "",
		_textField: "txt_x1y1",
		x: 0,
		y: 0,
	},
	x2y1: {
		name: "x2y1",
		piece: "",
		_textField: "txt_x2y1",
		x: 0,
		y: 0,
	}
}

Object.entries(main.x1y1); which produces in the latest version of Chrome the following:

  1. (5) [Array(2), Array(2), Array(2), Array(2), Array(2)]

  2. 0: (2) [“name”, “x1y1”]

  3. 1: (2) [“piece”, “”]

  4. 2: (2) ["_textField", “txt_x1y1”]

  5. 3: (2) [“x”, 0]

  6. 4: (2) [“y”, 0]

  7. length: 5

  8. proto: Array(0)