Sergino
Sergino

Reputation: 10818

How to select value from array by key

I have such array in my class:

   stuff = [
        { ['xwz']: 'https://site1.com' },
        { ['erx']: 'https://site2.com' },
        { ['qwery']: 'https://someurl-here.com' },
        { ['stuff']: 'http://morestuffhere.com' }
    ]

I want to get the value('https://...') by passing the key like this.stuff['xwz'] but didn't work this way. Any ideas?

Upvotes: 1

Views: 3764

Answers (2)

ChickenFeet
ChickenFeet

Reputation: 2813

This should do the job.

// declare as
stuff = {
    'xwz': 'https://site1.com',
    'erx': 'https://site2.com',
    'qwery': 'https://someurl-here.com',
    'stuff': 'http://morestuffhere.com'
 }

// Access with
this.stuff['xwz'] // returns 'https://site1.com'

Upvotes: 3

Pato Salazar
Pato Salazar

Reputation: 1477

So the way you have written your code you need to access the array index first and then the object... like this (assuming you are using a class property)

this.stuff[0].xwz // This will retrieve the first array element

Now, why you are not using just an object for this task, like this

 stuff = {
    xwz: 'https://site1.com',
    erx: 'https://site2.com',
    qwery: 'https://someurl-here.com',
    stuff: 'http://morestuffhere.com'
 }

    this.stuff.xwz

Upvotes: -1

Related Questions