正确存储对象列表的方式

时间:2017-02-14 11:05:48

标签: javascript oop

我在下面有一个国家/地区列表,它是一个对象。

enter image description here

我还有一个市场清单:

enter image description here

我想要它,以便在France对象中有另一组Object列出所有扇区。我尝试将列表保存为Country.list [country] [sector] = self;但无济于事。我怎么克服这个?代码:

enter image description here

实际上,我想创建一个多维JS对象,它进入一个特定的国家,然后进入该国的部门。

3 个答案:

答案 0 :(得分:1)

您可能希望将字符串(非变量)作为扇区的键

Country.list[country]['sector'] = self; // notice, it is string

答案 1 :(得分:0)

不清楚你在问什么..

如果您需要Market与法国相关的所有行业并将其添加到Country列表..那么您可以试试这个。

 var sectors = [];

    $.each(Market.list, function(key, value){
     if(value.country == "France"){
       sectors.push(value.sector);
      }
    });

这将在France数组中添加与sectors相关的所有扇区。现在我们将此数组分配给主Country.list

Country.list[France].allSectors = sectors ;

答案 2 :(得分:0)

您的所有属性当前都设置在同一个平面对象中。你的意思是你必须嵌套它们。

Country中,您必须创建一个新对象,并将其分配给Country.list中的相应属性(如果它尚不存在)。该对象将为该部门提供相同的处理方式。

以下代码(在Country中)肯定会比我糟糕的解释清楚:-)

if(!Country.list[country])Country.list[country]={};
Country.list[country][sector]=self;

请注意,country属性应设置为列表中的父对象:

if(!Country.list[country]){
   Country.list[country]={'country' : country};
}
Country.list[country][sector]=self;
相关问题