创建2d javascript数组列上选择的数据子集



对于基本问题和糟糕的词汇,我很抱歉,我是javascript的新手。我有一个数据数组,我想创建该数据的一个子集,基于选定的列。数据的前几行,例如:

0: {ID: 3607, Name: 'Alamo', Funds: 52933955,收入:9160109,BAT: 5,…}

1: {ID: 3539, Name: 'Alvin', Funds: 6128147,收入:964083,BAT: 0,…}

2: {ID: 3540, Name: 'Amarillo', Funds: 12450969,收入:1716038,BAT: 0,…}

我想从列0、1、2和4 (ID、Name、Funds和BAT)创建一个新的数组。在下面的代码中,toolData是从原始数据集(toolData.json)创建的数组,而tableData是我试图从所选数据创建的数组。selections包含我想拉入新数组的列号。

var getData = () => axios.get('toolData.json')
.then(res => res.data)
.then(data => {

var toolData = data;
console.log(toolData);

var tableData = [];
var selections = [0,1,2,4];
for (i=0; i < toolData.length; i++)
{
tableData[i] = toolData[i];
for (j=0; selections.length; j++)
{ 
k = selections[j],
tableData[i][j] = toolData[i][k]
}
}
console.log(tableData);

这个特定的代码片段根本不起作用,我假设我以某种方式创建了一个无限循环。如果我注释掉tableData[i] = toolData[i];,那么问题就解决了,但是代码仍然不能工作。console.log(toolData);给了我我正在寻找的(完整的数据面板),但console.log(tableData);给出了错误:

javascript.js:42 Uncaught (in promise) TypeError: Cannot set properties of undefined (setting '0')
at javascript.js:42

最终我希望用户能够选择他们想要包含在新数组中的列,但在我解决这个难题之前,我需要解决这个难题。

嗯,从你所说的来看,数组中的每个索引都是一个对象。arr[0][0]==undefinedbutarr[0]['ID']==3607

function newSubset(arr,dataToSelect){
//arr is the fetched array, dataToSelect is an array of the keys(like ID,Name...) that you want from the array
return arr.map(obj=>{
var toReturn={} //object that would give each desired key for each part in arr
dataToSelect.forEach(key=>toReturn[key]=obj[key]) //placing wanted keys in toReturn
return toReturn
})
}
//usage
var getData = () => axios.get('toolData.json')
.then(res => res.data)
.then(data => { 
var wantedKeys=["ID","Name","Funds","BAT"]
console.log(newSubset(data,wantedKeys))
//rest of your code here
<<p>

生活例子/strong>

var dataArray=[{ID: 3607, Name: 'Alamo', Funds: 52933955, Revenues: 9160109, BAT: 5},   {ID: 3539, Name: 'Alvin', Funds: 6128147, Revenues: 964083, BAT: 0},   {ID: 3540, Name: 'Amarillo', Funds: 12450969, Revenues: 1716038, BAT: 0}]
function newSubset(arr,dataToSelect){
//arr is the fetched array, dataToSelect is an array of the keys(like ID,Name...) that you want from the array
return arr.map(obj=>{
var toReturn={} //object that would give each desired key for each part in arr
dataToSelect.forEach(key=>toReturn[key]=obj[key]) //placing wanted keys in toReturn
return toReturn
})
}
console.log(newSubset(dataArray,["ID","Name","Funds","BAT"]))

数据为JSON对象。它不是按数字索引,而是按名称索引。

也建议使用内置的map函数。

const tableData = toolData.map(row => ({
ID: row.ID,
Name: row.Name,
Funds: row.Funds,
BAT: row.BAT
}));

如果你想让新的toolData数组包含数组而不是对象,你可以这样做:

const tableData = toolData.map(row => [
row.ID,
row.Name,
row.Funds,
row.BAT
]);

相关内容

  • 没有找到相关文章

最新更新