0

When data-person has a value of 80 I want to show the content that is in the object with the matching key, ie. to access { "name": "Jhon Doe"} and show in the HTML.

<div id="people" data-person="80"></div>
var people = {"80": { "name": "Jhon Doe"}}
var obj = JSON.parse(people);

How I can get this? Thank You!

3
  • Do you want to access { "name": "Jhon Doe"} ? Commented Jan 11, 2018 at 11:15
  • @Rayon yes! :). Commented Jan 11, 2018 at 11:16
  • @rory-mccrossan thanks for you edition! Commented Jan 11, 2018 at 11:25

2 Answers 2

3

Using jQuery data() and having multiples

var people = {
  "80": {
    "name": "Jhon Doe"
  },
  "90": {
    "name": "Fred Flinstone"
  }
}


$('[data-person]').text(function() {
  return people[$(this).data('person')].name
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="people" data-person="80"></div>
<div id="people2" data-person="90"></div>

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

1 Comment

Use common classes on the children and do something like: $('[data-person]').each(function(){ var person = people[$(this).data('person')]; $(this).find('.person-name').text(person.name);})
1

Basically you are trying to access a object which is property of an object.

Use Element.dataset to access the value from data-* attribute and use Bracket notation to access the value.

Note: JSON.parse is not needed at all. Purpose of JSON.parse to parse JSON(Text) as Object

Edit: To set the text, use jQuery.text or Element.textContent

var people = {
  "80": {
    "name": "Jhon Doe"
  }
};
var element = document.getElementById('people');
var key = element.dataset.person;
element.textContent = people[key].name;
<div id="people" data-person="80"></div>

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.