无法读取对象数组上未定义的属性“推”(Typeof显示对象)

时间:2019-04-16 22:03:04

标签: javascript arrays reactjs object ecmascript-6

这是该帖子经过澄清后的重新发布:Cannot read property 'push' of undefined on an Array of objects

但是本质上我下面是

let foo = {
   "a" : [],
   "b" : [],
   "c" : []
}

let fee = {
   {
     'name':'apple'
   },
   { 
     'name':'banana'
   }
}

let fum = {
   'apple':'a',
   'banana':'b'
}


for(let index in fee){
   let current = fee[index];
   foo[fum[current.name]].push(current);
}

这告诉我我不能推送到undefined。 当我登录typeof foo[fum[current.name]]时,得到的是“对象”而不是预期的Array。

2 个答案:

答案 0 :(得分:1)

Your code doesn't work because fee needs to be an array:

let fee = [
   {
     'name':'apple'
   },
   { 
     'name':'banana'
   }
];

Now your code should work.

答案 1 :(得分:-1)

fee must be an array. Try this

let foo = {
   "a" : [],
   "b" : [],
   "c" : []
}

let fee = [
   {
     'name':'apple'
   },
   { 
     'name':'banana'
   }
]

let fum = {
   'apple':'a',
   'banana':'b'
}


for(let index in fee){
   let current = fee[index];
   foo[fum[current.name]].push(current);
}