简体   繁体   English

使用push和forEach创建数组和对象

[英]create array and object using push and forEach

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) grandParent是未定义的,我要实现的是每个祖父母都有一个parent属性,每个父母都有孩子(对象数组也是如此)

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?

forEach doesn't return anything, you must use map instead. forEach不返回任何内容,而必须使用map Also push returns the new size of the array, to return a new array use concat 同时push返回数组的新大小,要使用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. 这样做的另一种方法是不从forEach返回任何内容,而只是更新原始数组。

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

console.log(grandParent)

From MDN docs of Array.prototype.forEach() 来自Array.prototype.forEach() MDN文档

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

.forEach does not return anything. .forEach不返回任何内容。 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) console.log(grandParent)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM