1

I have some date like this:

const data = {
  first: {
    segment: 'first',
    segment_id: '257ad548-6fee-47c1-afbc',
    placeholder: 'Some text'
  },
  second: {
    segment: 'second',
    segment_id: '373273a0-208f-4c3f-905b',
    placeholder: 'Some random text'
  },
  third: {
    segment: 'third',
    segment_id: '26e96613-1180-4961-b775',
    placeholder: 'Another random text'
  },
  fourth: {
    segment: 'fourth',
    segment_id: '03451a57-8d95-4113-b109',
    placeholder: 'Totally random text'
  },
};

And a selext box:

<select id="segments">
  <option selected="selected" value="257ad548-6fee-47c1-afbc">first</option>
  <option value="373273a0-208f-4c3f-905b">second</option>
  <option value="26e96613-1180-4961-b775">third</option>
  <option value="03451a57-8d95-4113-b109">fourth</option>
</select>

How can I get data from the object based on the selected value? This is what I have tried:

document.getElementById('segments').onchange = function () {
    selectedSegment = this.options[this.selectedIndex].text;
    console.log(data.selectedSegment.placeholder); // Not working - it's undefined
    // I'm looking for this value in the data object: data."selected text".paceholder
}

JsFiddle

Hope my question makes sense. :-) Thank you.

Meek
  • 3,086
  • 9
  • 38
  • 64
  • `data[selectedSegment].placeholder` – T.J. Crowder Mar 08 '22 at 11:27
  • There's no need, your question is already answered in the [linked question](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable)'s answers. But I thought it would be helpful to point out how those answers apply to your specific case. – T.J. Crowder Mar 08 '22 at 11:51

0 Answers0