简体   繁体   English

Javascript - 如何拆分多维数组数据并利用它

[英]Javascript - How to split multidimensional array data and utilise it

I have some data which I have pulled from an external file, loaded as strings and split it into arrays.我有一些从外部文件中提取的数据,作为字符串加载并将其拆分为数组。 I would like to now utilise this data, I'm unsure if the best way to go about doing this is to just access the parallel arrays or to create objects with 3 different named values.我现在想利用这些数据,我不确定这样做的最佳方法是仅访问并行数组还是创建具有 3 个不同命名值的对象。

I attempted to do the former, here is a picture of my data logging to console for reference:我试图做前者,这是我的数据记录到控制台的图片以供参考:

数据

And here is the code I attempted:这是我尝试的代码:

  for(let i = 0; i < problem.length; i++) {
   for(let j = 1; j < problem.length; j++) {
    for(let k = 2; k < problem.length; k++) {
     id = problem[i];
     posX = problem[j];
     posY= problem[k];
    }
   }
  }

Where problem is the split string array, this does not work, and I'm quite confused on the best way to manipulate this sort of data, of which i feel is a very important skill and any guidance is appreciated!问题在于拆分字符串数组,这不起作用,而且我对操作此类数据的最佳方法感到非常困惑,我认为这是一项非常重要的技能,感谢任何指导!

If it matters at all I will be 'hoping' to easily call upon the one set of 3 values at a later date to visualise the data.如果这很重要,我将“希望”在以后轻松调用一组 3 个值来可视化数据。

It's not easy to answer because you don't explain the output format you want to get (because you are not sure) and you didn't ask an accurate question, it's more about preferences, so I can tell you what I think but it may depend on each person.不好回答,因为你没有解释你想要得到的输出格式(因为你不确定)并且你没有问一个准确的问题,更多的是关于偏好,所以我可以告诉你我的想法但它可能因人而异。 So I hope my answer will help you somehow.所以我希望我的回答能以某种方式帮助你。

Reading your code, I assume index 0 in the array is an id, index 1 is posX and index 2 is posY.阅读您的代码,我假设数组中的索引 0 是一个 id,索引 1 是 posX,索引 2 是 posY。

So, if it were me, in order to manipulate this data easily here is how I would transform the data:所以,如果是我,为了轻松操作这些数据,我将如何转换数据:

 data = [ ["30", "104", "153"], ["31", "104", "161"], ["32", "104", "169"], ["33", "90", "165"], ["34", "80", "157"], ["35", "64", "157"], ] const result = data.map(item => ( { id: item[0], posX: item[1], posY: item[2], } )) console.log("ORIGINAL DATA", data) console.log("NEW DATA", result)

A benefit is it would allow you to do data[15].posX instead of data[15][1]一个好处是它可以让你做 data[15].posX 而不是 data[15][1]

(but again, it's just my preference, there may be tens of different ways) (但同样,这只是我的偏好,可能有数十种不同的方式)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM