简体   繁体   中英

How can I loop through an array of object and get one property element out of the two objects listed inside the array?

I have my array of object bellow.

const Articles = [
    {
        id: 1,
        article1: 1,
        title1:'Trust',
        name1:'Pericles',
        date1:'Dec 2, 2022',
        text1: 'Lorem ipsum dolor sit consectetur. minima in quae dolores quis fugit officia, quia at quam ipsum iste suscipit, eum, veniam eaque voluptas?',
    },
    {
        id: 2,
        article2: 2,
        title2:'Love',
        name2:'Billey',
        date2:'Dec 2, 2022',
        text2: 'minima in quae dolores quis fugit officia, quia at quam ipsum iste suscipit, eum, veniam eaque voluptas?',
    }

]

I have a function and I am trying to select Articles.title1 through mapping

function  arc(){
   Articles.map((element, index)=>{    
   console.log(element.title1) 
})

I get "Trust" for the title1 and that's all I needed but, I'm getting undefined for the other. Is there a way I can have just title1 ? Thank you.

I have also tried for loop:

for(let i = 0; i < Articles.length; i++){
    console.log(Articles[i].title1)
}

and get the same result.

Use title as the key instead of title1 and title2 .

And for other keys, you should do the same:

{
  id: 1,
  article: 1,
  title:'Trust',
  name:'Pericles',
  date:'Dec 2, 2022',
  text: 'Lorem ipsum dolor sit consectetur. minima in quae dolores quis fugit officia, quia at quam ipsum iste suscipit, eum, veniam eaque voluptas?',
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM