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

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Naim
  • 471
  • 1
  • 4
  • 14
  • `for (let i = 0; i <= result.length; i++) {console.log(result[i].name);}` doesn't look like it should throw a error – nicael Mar 28 '22 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. – Dave Newton Mar 28 '22 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})));` – pilchard Mar 28 '22 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. – Naim Mar 28 '22 at 21:59
  • @Naim, then your data is not as you posted, or you failed to return properly from your callback. [jsfiddle](https://jsfiddle.net/Lktb1vhp/) – pilchard Mar 28 '22 at 22:10
  • @pilchard Sorry! It does work with ```map()``` as well! (removed comment prior) But I am a bit confused since you mentioned in mohsen's answer that ```map``` should not be used. Maybe implementation was the issue not the function itself? – Naim Mar 28 '22 at 22:16
  • 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()](https://stackoverflow.com/questions/34426458/javascript-difference-between-foreach-and-map) for more discussion. – pilchard Mar 28 '22 at 22:18

3 Answers3

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));
Peterrabbit
  • 2,166
  • 1
  • 3
  • 19
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>
-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);
});
mohsen ab
  • 27
  • 4
  • 3
    Don't use `map()` if you're not going to use the returned array, this should just be `forEach()` – pilchard Mar 28 '22 at 21:09
  • 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 , ! – mohsen ab Mar 28 '22 at 21:12
  • 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. – pilchard Mar 28 '22 at 21:14