Carl Pericles
Carl Pericles

Reputation: 1

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.

Upvotes: 0

Views: 55

Answers (1)

lv_
lv_

Reputation: 246

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?',
}

Upvotes: 1

Related Questions