'How to get array name from json encode to javascript on console.log?
I have an array. I converted php array inside JavaScript. I want to get array's name for my select option. How to get array name on console log?
My code is below;
<script>
var users= <?php echo json_encode($users) ?>;
console.log(users);
</script>
[{0: {id:1, name: Alex, email: [email protected]}},
{1: {id:2, name: Jane, email: [email protected]}}]
This is what I get.
But this is what I want.
Alex
Jane
Can you help me please ?
Solution 1:[1]
You got use flatMap()
const users = [{0: {id:1, name: "Alex", email: "[email protected]"}},{1: {id:2, name: "Jane", email: "[email protected]"}}]
const parsedUsers = users.flatMap(user=>Object.values(user));
parsedUsers.forEach(user=>console.log(user.name));
Solution 2:[2]
you can use @json blade directive :
<script>
var users= @json($users);
console.log(users);
</script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ADyson |
| Solution 2 | Ahmed Atoui |
