在构造函数中迭代对象内部的对象?

时间:2018-04-04 15:22:27

标签: javascript arrays loops object constructor

在构造函数中我试图创建一个对象。

在对象中,我已经在为某些数组使用map函数。

当我尝试迭代一个对象时出现了挑战,因为我不能在对象上使用map函数。我也尝试在这个对象中使用for in函数但看起来,在对象创建中使用for in是无效的JS。

我的目标是遍历individualData对象(就像数组的普通地图函数一样)。

我尝试在地图功能中移动data: data.individualData。这对我的预期结果不起作用。

这是我的代码:



labelsArray = ['Breakfast', 'Lunch', 'Dinner'];

data = {
  miniLabelsArray: ['Egg', 'Soup', 'Steak'],
  type: ['Vegetarian', 'Vegan', 'Normal'],
  individualData: [{
    John: ['1', '2', '3'],
    Paul: ['10', '20', '30'],
    Kate: ['100', '200', '300']
  }]
};

function CreateData(data, someNewObj) {
  
  this.someNewObj = {
    labels: labelsArray,
    datasets: 
      data.miniLabelsArray.map((miniLabelsArray, i) => ({
        miniLabel: data.miniLabelsArray[i],
        type: data.type[i],
        })),
        data: data.individualData
    };
  };

var testing = new CreateData(data);

console.log('testing', testing.someNewObj);




https://codepen.io/anon/pen/qoMdoe?editors=1111

预期结果:

 ...
  "datasets": [
    {
      "miniLabel": "Egg",
      "type": "Vegetarian",
      "data": ["1", "2", "3"]       // DIFFERENCE HERE
    },
    {
      "miniLabel": "Soup",
      "type": "Vegan",
      "data": ["10", "20", "30"]       // DIFFERENCE HERE
    },
    {
      "miniLabel": "Steak",
      "type": "Normal",
      "data" :["100", "200", "300"]       // DIFFERENCE HERE
    }
  ...

由于

2 个答案:

答案 0 :(得分:2)

我将您的方法更新为This。

datasets: data.miniLabelsArray.map((value, index)=>({
  miniLabel: value,
  type: data.type[index],
  data: data.individualData[0][keys[index]]
}))

重要的是var keys = Object.keys(data.individualData[0])

data: data.individualData[0][keys[index]]



labelsArray = ['Breakfast', 'Lunch', 'Dinner'];

data = {
  miniLabelsArray: ['Egg', 'Soup', 'Steak'],
  type: ['Vegetarian', 'Vegan', 'Normal'],
  individualData: [{
    John: ['1', '2', '3'],
    Paul: ['10', '20', '30'],
    Kate: ['100', '200', '300']
  }]
};

function CreateData(data, someNewObj) {
  //get keys from [individualData] property
  var keys = Object.keys(data.individualData[0])
  this.someNewObj = {
    labels: labelsArray,
    // here we map every [miniLabelsArray] value and get the [type] and [individualData] depending on the index that we are.
    datasets: data.miniLabelsArray.map((value, index)=>({
      miniLabel: value,
      type: data.type[index],
      // here we get the real key of [data.individualData] using the key we took at the beginning like this : keys[index], and with that key we get the value in [data.individualData[0]]
      data: data.individualData[0][keys[index]]
    }))
      
    };
  };

var testing = new CreateData(data);

console.log('testing', testing.someNewObj);




答案 1 :(得分:0)

您应该能够创建一个仅包含如下数字的individualdata数组:

let individualdata = [];
for (let d in data.individualData) { 
    individualdata.push(data.individualData[d]);
}

将其放在CreateData()功能的顶部,并将data: data.individualData替换为data: individualdata