将对象推入数组会导致TypeError

时间:2016-07-13 18:36:23

标签: javascript arrays

我有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()中创建一个新对象吗?

3 个答案:

答案 0 :(得分:2)

试试这个:



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

答案 1 :(得分:0)

你可以像TimoSta所说的那样做,但用reduce代替第一张地图:



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).reduce(function(previous, type) {
  return previous.concat(values[type].map(function(item) {
    return {
      name: type,
      field: item.field,
      descriptiom: item.description,
      key: 'school'
    };
  }));
}, []);

console.log(out);




希望有所帮助

答案 2 :(得分:0)

您可以使用Array#reduceArray#map获取数组中的所有对象。

var 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' }] },
    array = Object.keys(values).reduce((r, k) => 
        r.concat(values[k].map(a =>
            ({ type: k, field: a.field, description: a.description, key: 'school' }))), []);

console.log(array);