0

What's wrong with my code below? grandParent is undefined, what I want to achieve is each grandparent have a property of parent, and each parent have child (arrays of object too)

like so

[{
  name: 'a',
  parent: [{
    name: 'b',
    child: [{
      name: 'c'
    }]
  }]
}]

below code doesn't work

let grandParent = []

_.times(5, () => grandParent.push({
  name: faker.name.findName(),
  parent: []
}))

grandParent = grandParent.forEach(function(o) {
  return o.parent.push({ name: faker.name.findName() })
})

console.log(grandParent) //why here is undefined?
Sharon Chai
  • 507
  • 1
  • 6
  • 20
  • 1
    Click `<>` and create a [mcve] - include lowdash or whatever framework you use – mplungjan Mar 13 '18 at 06:08
  • it is `undefined` because `Array.prototype.forEach` returns `undefined`. You don't need to reassign `grandParent`. Also you don't need to return from `forEach` callback. – Yury Tarabanko Mar 13 '18 at 06:11

3 Answers3

0

forEach doesn't return anything, you must use map instead. Also push returns the new size of the array, to return a new array use concat

grandParent = grandParent.map(function(o) {
  return o.parent.concat([{ name: faker.name.findName() }])
})

console.log(grandParent)

Other way to do it is to not return anything from forEach and just update the original array.

grandParent = grandParent.forEach(function(o) {
    o.parent.push({ name: faker.name.findName()})
})

console.log(grandParent)
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
0

From MDN docs of Array.prototype.forEach()

Return value: undefined

let grandParent = [
{ name: 'grandname0',  parent: [] },
{ name: 'grandname1',  parent: [] },
{ name: 'grandname2',  parent: [] },
{ name: 'grandname3',  parent: [] },
{ name: 'grandname4',  parent: [] }
];


grandParent.forEach(function(o) {
  
  o.parent.push({ name: 'parent1' });
  
});
console.log(grandParent);
wscourge
  • 10,657
  • 14
  • 59
  • 80
0

.forEach does not return anything. using the map function will help. You code should look something like this.

let grandParent = []

_.times(5, () => grandParent.push({
  name: faker.name.findName(),
  parent: []
}))

grandParent = grandParent.map(function(o) {
  return o.parent.concat({ name: faker.name.findName() })
})

console.log(grandParent)