如何创建对象列表的javascript数组

How do I create a javascript array of lists of objects?

本文关键字:javascript 数组 列表 创建对象      更新时间:2023-09-26

我需要创建一个列表字典。这在Javascript中可能吗?我正在寻找可以为功能/子功能对添加对象并迭代功能/子特征集合的功能。我的功能/子功能数据是一系列整数对:

[1,2], [1,3], [1,23], [2,4], [2, 12], ....

其中,第一个数字是特征索引,第二个数字是子特征索引。这些对中的每一个都可以有一个对象列表。我想按特征索引迭代列表,按对象迭代列表。类似的东西

forEach( item where feature index == someIndex, function(foo) {
     forEach (item[someindex, foo.index] , function(bar) {
             display bar.prop1, bar.prop2, ....

我将进行数据库调用,并将结果作为项添加到此结构中。

这个结构是在模仿我在.Net中使用的一个字典,该字典使用元组作为键,使用对象列表作为值。声明是:

Dictionary <tuple[], list<myobject>>

谢谢,

Jerry

一个简单的解决方案就是简单的嵌套数组,所以类似

var arr = [[2,3]];

因此,每次推送到数组时,只需添加一个新数组作为条目

arr.push([1,2]);

然后,我会保留一个单独的阵列来存储实际的功能/子功能,并直接使用数字访问它们。所以类似于:

arr.forEach(function(item) {
    if (item[0] == someIndex) {
        subfeatures[item[1]].forEach(function(feature) {
            // Do something with the feature
        });
    }
});

希望这能让你走上正确的方向!

这个例子可能比您需要的要多一些。但也许你会发现好处。

//Object representing a Feature
function Feature(featureID, subFeatureID, list)
{
  this.featureID = featureID;
  this.subFeatureID = subFeatureID;
  this.list = list;
}
//Object to hold features
function FeatureCollection()
{
    this._collection = new Array();
}
//Augment the FeatureCollection prototype

FeatureCollection.prototype.add = function(feature)
{
    this._collection.push(feature);
};
FeatureCollection.prototype.foreach = function(someIndex, listFunction)
{
  //For each feature set, loop within the collection
  //until the someIndex is found
  for(var i=0,length=this._collection.length;i<length;i++)
  {
      //Store a local scoped variable of the feature
      var feature = this._collection[i];
      if(feature.featureID === someIndex)
      {
        //For each of the object within the feature's list
        //invoke a function passing feature as 'this'
        for(var x=0,xlength=feature.list.length; x<xlength;x++)
        {
          listFunction.call(feature, feature.list[x]);
        }
        break;        
      }
  }
}
//Create a feature collection
var featureCollection = new FeatureCollection();
//Create a new feature
var testFeature = new Feature(1,2,["hello","world"])
//Add the feature to the collection
featureCollection.add(testFeature)
//Iterate the collection invoking the provided anonymous
//function if the index passed matches
featureCollection.foreach(1, function(listItem)
{
  console.log("FeatureID: " + this.featureID + " ListItemValue:" + listItem)
});

http://jsbin.com/firiquni/1/edit

如果你不需要任何花哨的东西,并且你知道这两个数组的极限,你可以做一个技巧。

有些人可能会认为它很俗气,另一些人则认为它很优雅。

您可以使用对象和散列,而不是使用数组。将这两个索引转换为字符串值,用作哈希键。

var myVals = {};
myVals["1,4"] = "Hi";
myVals["9,5"] = "There";
for (var i = 0; i < 10; i++) {
  for (j = 0; j < 10; j++) {
    var key = i + "," + j;
    var val = myVals[key];
    if (val) {
      // do something
    }
}