Home > Software engineering >  How to get an element inside the array
How to get an element inside the array

Time:12-09

I want to get only the title from my array but I’m not sure how

My array :

Let books = [
{title= “harry potter”,
author=“jk Rowling”,
},
{title= “another title”,
author=“another author”,
},
{title= “3rd title”,
author=“3rd author”,
},
]

And because I’m trying to get every each of the titles I used the forEach function and I tried it like this :

books.forEach(element => console.log (element));

And then I tried to change the element with the

[books].title 

But I get an error that says that doesn’t work with arrow function.

CodePudding user response:

First lets fix your books array i assume your making JSON type array for this your code must be like this

let books = [
{"title": "Harry",
"author": "JK"
},
{"title": "Another title",
"author": "Another author"}
]

Then you can simply map that array using .map function

console.log(books.map((data)=>{return data.title}));

the output will be in Array with all title elements.

Output: ['Harry', 'Another title']

CodePudding user response:

First, Let is not a valid JavaScript keyword; let is. Also, in JavaScript object key-value pairs are separated by : not by =.

You can use the Array#map method to achieve your objective as follows:

const books = [{title:"harry potter",author:"jk Rowling"},{title:"another title",author:"another author"},{title:"3rd title",author:"3rd author"}],

      titles = books.map(({title}) => title),
      authors = books.map(({author}) => author);
      
console.log( titles, authors );

CodePudding user response:

To begin with, the array is not a correct JS array, you should replace = by :. Then you can use map if you want to transform the array:

let books = [
  {
    title: "harry potter",
    author: "jk Rowling",
  },
  {
    title: "another title",
    author: "another author",
  },
  {
    title: "3rd title",
    author: "3rd author",
  },
]

let titles = books.map(book => book.title);
console.log(titles); // ["harry potter", "another title", "3rd title"]

CodePudding user response:

You can simply do something like this

books.forEach( ({title}) => console.log (title));

CodePudding user response:

I think from this you can get your answer so you have to create a map like this

var objArray = [{"firstname":"bbb","userName":"bbb1","title":"","created_by_user_id":"-1","enabled":"true","lastname":"AC","last_connection":"","password":"","manager_id":"0","id":"14","job_title":"job1","last_update_date":"2018-08-08 13:35:56.996"},{"firstname":"aaa","icon":"icons/default/icon_user.png","creation_date":"2018-08-08 13:35:56.876","userName":"aaa1","title":"","created_by_user_id":"-1","enabled":"true","lastname":"AH","last_connection":"","password":"","manager_id":"0","id":"9","job_title":"job2","last_update_date":"2018-08-08 13:35:56.876"}];

let result = objArray.map(o => ({id: o.id}));
console.log(result);
  • Related