How can I access JavaScript object in array?

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'}]

Upvotes: 0

Views: 66

Answers (2)

Adrian Brand
Adrian Brand

Reputation: 21658

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'));

Upvotes: 0

qelli
qelli

Reputation: 2077

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.

Upvotes: 2

Related Questions