2

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: alex@gmail.com}},

{1: {id:2, name: Jane, email: jane@gmail.com}}]

This is what I get.

But this is what I want.

Alex

Jane

Can you help me please ?

ADyson
  • 57,178
  • 14
  • 51
  • 63
Sevil
  • 21
  • 4
  • If you only want the name attribute, you can use `Array.map()` to only return that attribute. – mykaf Mar 30 '22 at 13:52
  • I put array names to select option. But this is the result: Alex, Jane Alex, Jane But I want like this. Alex Jane (per option must have one name) – Sevil Mar 30 '22 at 14:17
  • 1
    So just loop through the data and get those specific properties. Or use a map technique like one of the examples below. Unclear what the problem is. have you tried anything? – ADyson Mar 30 '22 at 14:20
  • But...where are you generating the select? Doesn't your blade view generate and populate this from a model, if it's Laravel? Not clear why you're diverting the data to JavaScript first. – ADyson Mar 30 '22 at 14:22
  • var users= ; var x = users.map(function(item) { return Object.values(item)[1] }) ///////////(I put name to option code below) var userList = document.createElement("select"); userList .id = "guest" + (i + 1) + "_age"; users.forEach(function(value) { var opt = document.createElement("option"); opt.textContent = x; userList.appendChild(opt); }); container2.appendChild(ageList); – Sevil Mar 30 '22 at 14:24
  • https://stackoverflow.com/questions/48967118/show-hide-multiple-divs-based-on-dropdown-selection-javascript/48967195#48967195 (I use this answer) – Sevil Mar 30 '22 at 14:34

2 Answers2

2

You got use flatMap()

const users = [{0: {id:1, name: "Alex", email: "alex@gmail.com"}},{1: {id:2, name: "Jane", email: "jane@gmail.com"}}]

const parsedUsers = users.flatMap(user=>Object.values(user));

parsedUsers.forEach(user=>console.log(user.name));
ADyson
  • 57,178
  • 14
  • 51
  • 63
-1

you can use @json blade directive :

<script> 
var users= @json($users);
        console.log(users);
</script>
Ahmed Atoui
  • 1,506
  • 1
  • 8
  • 11