我有我的values对象

values = {
    'student': [{
        'field': 'prefix',
        'description': 'First name'
    }, {
        'field': 'suffix',
        'description': 'Last name'
    }, {
        'field': 'student_email',
        'description': 'Email address'
    }],
    'classes': [{
        'field': 'course_code',
        'description': 'Course code'
    }]
}


我正在尝试使每个对象都属于“学生”和“班级”。一旦抓住,我试图创建一个看起来像这样的新对象

{type:'student', field:'prefix', description:'First Name', key:'school'}


然后将该对象推入新数组。这是我到目前为止所拥有的...

const array = [];

for(const v in values) {
    array.concat(values[v].map(obj => {
       console.log(obj); // grabs each obj successfully
       array.push({
           type: v,
           description: obj.description,
           field: obj.field,
           key: 'school'
       });
    });
}


现在,它抛出TypeError: Cannot read property 'split' of undefined。我究竟做错了什么?我不能在.map()内部创建一个新对象吗?

最佳答案

尝试这个:



var values = {'student':[{'field':'prefix','description':'Firstname'},{'field':'suffix','description':'Lastname'},{'field':'student_email','description':'Emailaddress'}],'classes':[{'field':'course_code','description':'Coursecode'}]};

var out = Object.keys(values).map(function(type) {
  return values[type].map(function(item) {
    return {
      name: type,
      field: item.field,
      descriptiom: item.description,
      key: 'school'
    };
  });
}).reduce(function(l, r) {
  return l.concat(r);
});

console.log(out);







或者,ES6 arrow functions更好:

var out = Object.keys(values).map((type) =>
  values[type].map((item) => ({
    name: type,
    field: item.field,
    descriptiom: item.description,
    key: 'school'
  })
}).reduce((l, r) => l.concat(r));

07-24 09:47
查看更多