0

My question is how can I Access the object in the array. As an example how can I access the property country?

var arr1 = [{country: "Schweiz", code: 'ch'},{country: "Deutschland", code: 'de'},{country: "Oesterreich", code: 'at'}]
Antonio Correia
  • 1,093
  • 1
  • 15
  • 22
  • which one do you like to get? – Nina Scholz May 28 '19 at 18:31
  • 3
    Maybe using `arr1[].country` ? – Shidersz May 28 '19 at 18:32
  • You need to be more concise. Do you want to return a country based on a specific country name? – Neil May 28 '19 at 19:15
  • Array is a list of objects (countries in your case), so you need to decide which object you want to pick from this list. To get the first object you could use arr1[0] where 0 is an index. To pick an object based on a criteria (e.g. country code), you could use Array.find function – novomanish May 28 '19 at 22:21

2 Answers2

2

The correct syntax to acces an array of objects property is:

array[index].objectProperty

So, with this said to access the country value of the first index you should use:

arr1[0].country  // Schweiz

So, for example, lets print out every country on your array:

var arr1 = [{
    country: "Schweiz",
    code: 'ch'
  },
  {
    country: "Deutschland",
    code: 'de'
  },
  {
    country: "Oesterreich",
    code: 'at'
  }
];

arr1.forEach((item)=>{
  document.write(item.country+"<br>");
})

Note: In the array structure you provided exists a syntax error. You are missing a comma, which is used to separate elements on your array.

Arrays are structures separated with commas, like this:

myArray = [1,2,3,4,5];

So, to separate each index, you need to use a comma. You have:

var arr1 = [{
        country: "Schweiz",
        code: 'ch'
    }, // First separator comma
    {
        country: "Deutschland",
        code: 'de'
    } { // MISSING COMMA HERE
        country: "Oesterreich",
        code: 'at'
    }

]

So, just separate the new element with a comma:

var arr1 = [{
        country: "Schweiz",
        code: 'ch'
    },
    {
        country: "Deutschland",
        code: 'de'
    }, // ADDED COMMA
    {
        country: "Oesterreich",
        code: 'at'
    }

]

Hope this helps with your question. Welcome to Stackoverflow.

k3llydev
  • 2,057
  • 2
  • 11
  • 21
0

If you know the index you just use the index

arr1[1].country;

If you want to look it up by country code you can find it

var arr1 = [{country: "Schweiz", code: 'ch'},{country: "Deutschland", code: 'de'},{country: "Oesterreich", code: 'at'}];

const getCountry = (array, code) => array.find(country => country.code === code);

console.log(getCountry(arr1, 'de'));
Adrian Brand
  • 20,384
  • 4
  • 39
  • 60