How to scan an array of objects and return their values in a string

Asked

Viewed 544 times

2

I have this vector of objects here:

var usuarios = [
 {
 nome: "Diego",
 habilidades: ["Javascript", "ReactJS", "Redux"]
 },
 {
 nome: "Gabriel",
 habilidades: ["VueJS", "Ruby on Rails", "Elixir"]
 }
];

and I need to return this:

O Diego possui as habilidades: Javascript, ReactJS, Redux
O Gabriel possui as habilidades: VueJS, Ruby on Rails, Elixir

How to do?

  • Have tried the use of foreach`s?

2 answers

3


With a simple for...of you read the array and its objects:

var usuarios = [
 {
 nome: "Diego",
 habilidades: ["Javascript", "ReactJS", "Redux"]
 },
 {
 nome: "Gabriel",
 habilidades: ["VueJS", "Ruby on Rails", "Elixir"]
 }
];

for(let u of usuarios){
   console.log("O "+ u.nome +" possui as habilidades: "+ u.habilidades.join(", "));
}

In the case of the array habilidades, used a .join() to separate items with a comma and space.

  • 1

    +1, very good answer, just did not understand why it was closed.

  • I tested it here and it worked, thanks. You can also do it using template strings, using E6.

  • @Danúbiovieiralima You can use template strings tb. Abs!

2

With jquery you can use $.each with the array Join

This if you intend to use on some page

Following example:

var usuarios = [
 {
 nome: "Diego",
 habilidades: ["Javascript", "ReactJS", "Redux"]
 },
 {
 nome: "Gabriel",
 habilidades: ["VueJS", "Ruby on Rails", "Elixir"]
 }
];

const percorrer = () =>{
  var texts = ''
  $.each(usuarios, (i, j) => {
    texts += `<p><strong>${j.nome}</strong> possui as seguintes habilidades: ${j.habilidades.join()}</p>`
  })
  
  $('.content').html( texts )
}

$(()=>{
  percorrer()
})
<script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>

<div class="content">
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.