[英]Array with defined key and multidimensional
我在没有帮助的情况下查看了其他类似的帖子,它们都从一个已经创建的多维数组开始,我想使用 .push 方法创建一个
我的数组是:
ItemsArray.push({
BMW:{Model:X5,Model:X6,Model:X3 },
Range Rover:{Model:Sports,Model:Venar}
});
汽车品牌由按钮定义,因此如果用户单击 Fiat,则列表会生成诸如{Model: Punto}
并使用Fiat:{Model: Punto}
推送到上述数组中。
我尝试使用: ItemsArray[CarName].Models.push
但它给出了错误
ItemsArray[CarName].Item' 未定义
您提供的部分代码将永远无法工作。 例如: BMW:{Model:X5,Model:X6,Model:X3 }
。 它构造了一个对象,并且您要添加相同的属性Model
三次。 结果是这个对象: { Model: X3 }
。 您必须为此使用数组而不是对象,就像我在下面的示例中所做的那样。
除此之外,使用数组来存储所有数据是不切实际的。 你会得到这样的数据结构:
[ { brand: 'BMW', models: [ name: 'X5' ] }, { brand: 'Fiat', models: [ name: '500' ] }, ]
现在,每当您想要向品牌添加模型时,您首先必须在数组中查找品牌属性与您想要添加模型的品牌相匹配的条目。 只有在这样做之后,您才能开始为品牌操纵模型。
我认为您想要做的是拥有一个具有每个品牌属性的对象。 在此属性下,您可以存储包含该品牌模型的数组。 我在下面的代码片段中模拟了一些东西。
const // This object will get an property per brand. modelsPerBrand = {}, // An array with the brand we support. brands = ['BMW', 'Ford', 'Fiat']; /** * This method will add a single model to a single brand. */ function addModelToBrand(brand, model) { const vehicles = modelsPerBrand[brand]; if (vehicles === undefined) { // Log a message or alternatively add the new brand to the modelsPerBrand object. console.log(`Unknown brand "${ brand }"`); return; } // Add the provided model to the array of models for the brand. vehicles.push({ name: model }); } /** * This method makes it easy to add multiple models at once to a * single car brand. */ function addModelsToBrand(brand, models) { if (modelsPerBrand[brand] === undefined) { console.log(`Unknown brand "${ brand }"`); return; } models.forEach(model => addModelToBrand(brand, model)); } // Create an empty array for each brand. It will result in an object // like this: // { // BMW: [], // Ford: [], // Fiat: [] // } brands.forEach(brand => modelsPerBrand[brand] = []); console.log('Object with brands: ', modelsPerBrand); // Add a single model to a brand. The object we have will now look // like this: // { // BMW: [ { name: 'X5' } ], // Ford: [], // Fiat: [] // } addModelToBrand('BMW', 'X5'); console.log('Object after adding BMW X5: ', modelsPerBrand); // Add a multiple models to a brand addModelsToBrand('Fiat', ['500', '500L']); console.log('Object after adding Fiat 500 and 500L: ', modelsPerBrand); // Add model to non-existing brand addModelsToBrand('KIA', 'Stinger'); // List all models for a brand: modelsPerBrand.Fiat.forEach(model => console.log(`Fiat ${ model.name }`));
或者,您可以使用Map
而不是vehiclesPerBrand
变量的对象,但我不确定您打算如何使用它。 这就是为什么我使用Object
代替。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.