A = {
region1: {
city1: [option1, option2, option3],
city2: [option1, option2, option3]
},
region2: {
city1: [option1, option2, option3],
city2: [option1, option2, option3]
}
How can I make city1 in region2 show up in console.log as a normal text or string ?
For example if I right A["region2"]["city1"][1] in console.log the result will be option2 and it will show up as normal text.
But if I write A["region2"]["city1"] the result will show all of the array inside of city1
I need city1 to show up in console.log plain without the array inside of it nor anything else (just like a normal text or string)
I mean the object city1 not the content of it just the object it self.
I need the result in console.log to be just like that (city1)
(not the content of city1)
This is an object-oriented approach involving the override of the toString() method
function Area(name, regionList) {
this.name = name;
this.regionList = regionList;
}
function Region(name, cityList) {
this.name = name;
this.cityList = cityList;
}
function City(name, optionList) {
this.name = name;
this.optionList = optionList;
}
Area.prototype.toString = function () {
return this.name;
};
Region.prototype.toString = function () {
return this.name;
};
City.prototype.toString = function () {
return this.name;
};
var city = new City('Lugano', ['lago', 'montagna']);
var region = new Region('Ticino', [city]);
var area = new Area('Svizzera', [region]);
console.log(area.toString());
console.log(area.regionList[0].toString());
console.log(area.regionList[0].cityList[0].toString());
You can get the object keys using the Object.keys(). Passing the A.region1 inside the function will return you the array ['city1', 'city2'] and then you can get the key that you want by its index.
const obj = {
'region1': {
'city1': ['option1', 'option2', 'option3'],
'city2': ['option1', 'option2', 'option3']
},
'region2': {
'city1': ['option1', 'option2', 'option3'],
'city2': ['option1', 'option2', 'option3']
}
}
console.log(Object.keys(obj.region1)[0]);
Join is there to rescue
console.log(A["region2"]["city1"].join(" "))
You can specify comma, space or anything you wish to split the elements inside join.
UPDATE
As the requirement is to display the key in console, you can traverse the keys of objects using Object.keys, and so I use it to find the index of the key with value "city1" and then use that index to print it. This way, you can specify any desired key name.
console.log(Object.keys(A["region2"])[Object.keys(A["region2"]).indexOf("city1")])