猿问

如何创建一个循环来创建对象,然后将这些对象推入数组?

所以我开始导入 4 个具有相同数据量的不同数组。


然后我做了一个类,认为这个类可以帮助我用导入的数据制作对象。


所以我的想法是,如果我遍历该类,它可以创建一个对象,该对象通过其索引包含所有 4 个数组的数据,然后将该对象推入一个数组。


我希望objectArray的最终结果看起来像...


[ {nn: "Lion", dat1: 4, dat2: 9, dat3: 10}, {nn: "Zebra", dat1: 5, dat2: 10, dat3: 7}, {nn: "Monkey", dat1: 2, dat2: 6, dat3: 14} ...etc. ]

// mock

const threeToType = {

   name: ["Lion", "Zebra", "Monkey"],

  data1: [     4,       5,        2],

  data2: [     9,      10,        6],

  data3: [    10,       7,       14],

};


const {name, data1, data2, data3} = threeToType; // require('./threeToType');


let objectArray = [];


class makeObj{

    constructor(nn, dat1, dat2, dat3){

        this._nn = nn;

        this._dat1 = dat1;

        this._dat2 = dat2;

        this._dat3 = dat3;

    }

}


for(let newObj, i = 0, tN = "", tD1 = 0, tD2 = 0, tD3 = 0; i<name.length; i++){


    tN = name[i];

    tD1 = data1[i];

    tD2 = data2[i];

    tD3 = data3[i];


    objectArray.push(newObj = new makeObj(tN, tD1, tD2, tD3));


}


console.log(objectArray);


慕哥9229398
浏览 125回答 4
4回答

梦里花落0921

为什么不只是简单地:const {name, data1, data2, data3} = require('./threeToType');let objectArray = []for (let i = 0; i < name.length; i++) {&nbsp; let newItem = { nn: name[i], tD1: data1[i], tD2: data2[i], td3: data3[i] }&nbsp; objectArray.push(newItem)}

MMMHUHU

获取您的nameArr, data1Arr, data2Arr, 和data3Arr来自/如何您希望 - 我已经为代码段使用了一些数据。mapcv使用索引(此处)迭代数组(此处未使用)中的项目idx。我们用它来idx从所有数组中检索“平行”项并从中创建一个对象。我们用括号 (和)包围对象,因为它是返回的,我们不希望浏览器认为它是代码 (是一个函数,但我们可以省略括号,在这里 - 我们使用它们)。()returnnameArr=["Zebra", "Lion", "Elephant"];data1Arr=[23, 12, 40];data2Arr=["Africa", "America", "India"];data3Arr=[true, false, true];objArr=nameArr.map((cv, idx)=>({&nbsp; name:nameArr[idx],&nbsp; data1:data1Arr[idx],&nbsp; data2:data2Arr[idx],&nbsp; data3:data3Arr[idx]}));console.log(objArr);.as-console-wrapper { max-height: 100% !important; top: 0; }

慕运维8079593

这是一个更通用的解决方案,假设您的输入数组基本上是表格的行(因为它们都具有相同的长度),并且您想要“翻转”或将它们反转为列。基本上是一个二维数组。我会将输入数组的名称保留在该算法之外。在 JS 中,没有简单的方法可以将变量的名称(如代码段中的“data1”)作为字符串获取。顺便说一句,您可以使用任意数量的数组来调用它,只要它们的长度都相同。const invertRows = (...rows) => {&nbsp; &nbsp; const numRows = rows.length;&nbsp; &nbsp; const numColumns = rows[0].length;&nbsp; &nbsp; const inverted = new Array(numColumns);&nbsp; &nbsp; for (let col=0; col < numColumns; col++) {&nbsp; &nbsp; &nbsp; &nbsp; inverted[col] = new Array(numRows);&nbsp; &nbsp; &nbsp; &nbsp; for (let row=0; row < numRows; row++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; inverted[col][row] = rows[row][col];&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return inverted;};const arr1 = [1,2,3];const arr2 = [3,4,5];console.log(invertRows(arr1, arr2));// Returns: [ [ 1, 3 ], [ 2, 4 ], [ 3, 5 ] ]

慕婉清6462132

我目前不太确定您在问什么,您当前的解决方案确实有效。这是转换数据结构的通用解决方案:// fromconst columns = {name: ["John Doe", "Jane Doe"], age: [42, 39]};// intoconst rows = [{name: "John Doe", age: 42}, {name: "Jane Doe", age: 39}];// and the other way around.const threeToType = {&nbsp; &nbsp;name: ["Lion", "Zebra", "Monkey"],&nbsp; data1: [&nbsp; &nbsp; &nbsp;4,&nbsp; &nbsp; &nbsp; &nbsp;5,&nbsp; &nbsp; &nbsp; &nbsp; 2],&nbsp; data2: [&nbsp; &nbsp; &nbsp;9,&nbsp; &nbsp; &nbsp; 10,&nbsp; &nbsp; &nbsp; &nbsp; 6],&nbsp; data3: [&nbsp; &nbsp; 10,&nbsp; &nbsp; &nbsp; &nbsp;7,&nbsp; &nbsp; &nbsp; &nbsp;14],};function columnsToRows(columns) {&nbsp; columns = Object.entries(columns);&nbsp; if (columns.length == 0) return [];&nbsp;&nbsp;&nbsp; const colLengths = columns.map(([,values]) => values.length);&nbsp; const maxColLength = Math.max(...colLengths);&nbsp;&nbsp;&nbsp; return Array.from({length: maxColLength}, (_, i) => {&nbsp; &nbsp; const row = Object.create(null);&nbsp; &nbsp; columns.forEach(([colName, values]) => row[colName] = values[i]);&nbsp; &nbsp; return row;&nbsp; });}function rowsToColumns(rows) {&nbsp; if (rows.length == 0) return {};&nbsp; const columns = Object.create(null);&nbsp; const colNames = new Set(rows.flatMap((row) => Object.keys(row)));&nbsp;&nbsp;&nbsp; colNames.forEach((colName) => columns[colName] = []);&nbsp; rows.forEach((row) => {&nbsp; &nbsp; colNames.forEach((colName) => columns[colName].push(row[colName]));&nbsp; });&nbsp;&nbsp;&nbsp; return columns;}console.log(columnsToRows(threeToType));console.log(rowsToColumns(columnsToRows(threeToType)));
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答