Reputation: 2415
I'm looping through object sliced
where I want to extract properties name
into theRest
variable. With code below I get an error Cannot read property name of undefined
My object sliced
gives me an array: [{name: 'Bart'},{name: 'Lisa'},{name: 'Maggie'}]
const theRest = sliced.map((item, i) => {
item[i].name;
})
Sorry for variables naming if tht's confusing but I hope you get an idea.
Upvotes: 0
Views: 2295
Reputation: 1670
The reason that you're getting an error is because when you're using .forEach(), item[i]
would be looking for an index in an object that isn't an array (sliced
is an array, item
is the currentValue in the array being processed). If you wanted to use your code, you should change item[i].name
to item.name
and it should work. I recommend that you use .map() instead to get the results you're looking for.
let arr = [{name: 'Bart'},{name: 'Lisa'},{name: 'Maggie'}];
let theRest = arr.map((item) => item.name);
console.log(...theRest);
Upvotes: 3