1

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

7
  • for (let i = 0; i <= result.length; i++) {console.log(result[i].name);} doesn't look like it should throw a error Commented Mar 28, 2022 at 20:52
  • 5
    Valid array indices for a non-sparse array are from 0 to length-1; your for-loop's terminating condition is incorrect. Commented Mar 28, 2022 at 20:53
  • 1
    Your attempt simply logs each name, not an array of names. If you want a new array with filtered objects simply map the array. console.log(result.map(({name})=>({name}))); Commented Mar 28, 2022 at 21:07
  • @nicael the = sign was the culprit as pointed out by Dave. Indices start from zero so you should keep on incrementing by 1 until you reach length - 1, otherwise you over iterate. Commented Mar 28, 2022 at 21:59
  • 1
    You should only use map() when you intend to create a new array because that is precisely what map does. While my example in the comment doesn't assign the returned array to a variable, it does utilize the returned array in the logging. Mohsen isn't using the array returned by map at all, but is simply using map() as if it were forEach(). see: JavaScript: Difference between .forEach() and .map() for more discussion. Commented Mar 28, 2022 at 22:18

3 Answers 3

1

Your for loop expression shouldn't go beyond 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));

Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

-1

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);
});

3 Comments

Don't use map() if you're not going to use the returned array, this should just be forEach()
why he get undefinde ? for , foreach() ? can you explain ? pilchard? , if u are used map() u can used other function , filter() , reduce() and other , and map() can be returned someting but in foreach() function you cant return , !
You're not assigning the returned array from map() to anything, and even if you did you aren't returning anything from your callback so the result array would be [undefined, undefined, undefined]. The OP was getting undefined because they were incorrectly accessing the object in their forEach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.