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'}]
4
  • which one do you like to get? Commented May 28, 2019 at 18:31
  • 3
    Maybe using arr1[<some_index>].country ? Commented May 28, 2019 at 18:32
  • You need to be more concise. Do you want to return a country based on a specific country name? Commented May 28, 2019 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 Commented May 28, 2019 at 22:21

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.