Home > Back-end >  Accessing properties individually in array of objects
Accessing properties individually in array of objects

Time:03-29

I have indeed found many questions that sounded similar but none worked in my case. Fairly new to OOP so please bear with me.

console.log(result) returns object below successfully:

[
  { name: 'horse', lid: 1 },   
  { name: 'cat', lid: 2 },  
  { name: 'dog', lid: 3 }  
]

I'd like the output to be

[
  { name: 'horse' },   
  { name: 'cat' },  
  { name: 'dog' }  
]

I know I can make the query fetch name only but what I am after is having full data set in result then choosing what properties to be displayed and what properties to be skipped for all objects.

My attempts so far

console.log(result[0].name result[1].name result[2].name); =>Success but what if I have 1000 objects ?

for (let i = 0; i <= result.length; i ) {console.log(result[i].name);} => Failed and returns Cannot read properties of undefined

result.forEach(arr => {
            for (const key in arr) {
            // console.log(arr[key].name); 
            console.log(arr[key]['name']);
            }
        });

Also failed and returns Cannot read properties of undefined

CodePudding user response:

Your for loop expression shouldn't go beyong length -1 (arrays are indexed from zero so last element index is length -1) so you should write it this way

const results = [
  { name: 'horse', lid: 1 },   
  { name: 'cat', lid: 2 },  
  { name: 'dog', lid: 3 }  
];

for (let i = 0; i < results.length; i  ) {console.log(results[i].name);}

And the forEach syntax should look like this

const results = [
  { name: 'horse', lid: 1 },   
  { name: 'cat', lid: 2 },  
  { name: 'dog', lid: 3 }  
];

results.forEach(res => console.log(res.name));

CodePudding user response:

the basic stuff

<script>
result=[
  { name: 'horse', lid: 1 },   
  { name: 'cat', lid: 2 },  
  { name: 'dog', lid: 3 }  
]

result.forEach(function(vl){
            console.log(vl.name);
        })
</script>

the array you lookin for

<script>
result=[
  { name: 'horse', lid: 1 },   
  { name: 'cat', lid: 2 },  
  { name: 'dog', lid: 3 }  
]

var newstuff=[];

result.forEach(function(vl){
 console.log(vl.name);
 newstuff.push(vl.name);
})

console.log(newstuff);
</script>

CodePudding user response:

I hope this helps

foreach cant return anything , and give u undifinde ,

use map() , if u want be return someting

const a = [
    { name: 'horse', lid: 1 },
    { name: 'cat', lid: 2 },
    { name: 'dog', lid: 3 },
];

a.map((items) => {
    const { name } = items;
    console.log(name);
});

  • Related