Home > OS >  how to show data after parse json
how to show data after parse json

Time:09-30

I try to load the list of users in the following code

<div id="users" data-users='[{"name":"one","userName":"user_one"}, 
{"name":"two","userName":"user_two"},{"name":"three","userName":"user_three"}]'></div>

How can I load the list of users in the values?

const users = document.querySelector("#users");
const json = JSON.parse(users.dataset.users);
var tribute = new Tribute({
 values: ** Load users this line **
});

CodePudding user response:

I see that you are assigning the result of JSON.parse(users.dataset.users) to the constant "json". This leads me to think you may misunderstand the resulting value from JSON.parse.

The data-set value on the div is currently json, so document.querySelector("#users") will return the json value.

JSON.parse(users.dataset.users) will then convert the json (users.dataset.users) into a JavaScript value, in this case returning the array of users I believe you wish you assign to the values property in the Tribute constructor.

I've switched your variable names below to make this more clear.

const json = document.querySelector("#users");
const users = JSON.parse(json.dataset.users);
let tribute = new Tribute({ values: users });

* As "the_previ" pointed out, without the definition for Tribute it's unclear to us what value the "values" property expects (ie. String, Number, Array). I've assumed you're looking to pass in the array of users.

CodePudding user response:

It's actually very simple using Lodash! You just need to import Lodash, and use the map function:

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>

<script>
const users = document.querySelector("#users");
var json = JSON.parse(users.dataset.users);

const userlist = (_.map(json, "name"));
</script>

userlist will be an array containing every "name" value.

If you want to use userName values instead, just replace name with userName on the map function!

  • Related