简体   繁体   English

在 Javascript 中访问(嵌套)对象和数组

[英]Accessing (nested) objects and arrays in Javascript

I'm not sure if I have a misconception on how to organise my array or on how to access it.我不确定我是否对如何组织阵列或如何访问它有误解。

Proposition is simple: Have an array of car makes and models and access them for display.提议很简单:拥有一系列汽车品牌和型号,并访问它们进行展示。

const carBrands = [
  {
    Audi: {
      models: ["A1", "A2", "A3", "A4"],
      unitsAvailable: 378,
    }
  },
  {
    BMW: {
      models: ["M1", "M2", "M3", "M4"],
      unitsAvailable: 413,
    },
  },
  {
    Honda: {
      models: ["H1", "H2", "H3", "H4"],
      unitsAvailable: 226,
    },
  }
];

I can access each model as such:我可以这样访问每个模型:

  carBrands.forEach((object, i) => {
    console.log(object, i)
  });

This a returns my objects and index fine:这 a 返回我的对象​​和索引很好:

Audi 0 BMW 1 Honda 2奥迪 0 宝马 1 本田 2

What I can't figure out is how to return:我想不通的是如何返回:

Make: Audi Models: A1, A2, A3, A4 Units available: 378品牌:奥迪 型号:A1、A2、A3、A4 可用单位:378

... for each of the 3 cars. ... 对于 3 辆车中的每一辆车。

I know I have to loop over the array and return for each loop the object key/value pairs.我知道我必须遍历数组并为每个循环返回对象键/值对。 But I'm having trouble with the correct syntax.但是我在使用正确的语法时遇到了问题。 Here's what I'm trying to figure out how to formulate:这是我试图弄清楚如何制定的内容:

  let modelsToDisplay = [];
  carBrands.forEach((object, i) => {
    modelsToDisplay.push(<li key={i}>Make/Model/Units of each object</li>);
  });

Thanks for helping out :)感谢您的帮助:)

carBrands.flatMap(Object.entries)
    .map(([key, { models, unitsAvailable }]) => `${key} ${models.join(", ")} ${unitsAvailable}`)
    .forEach(v => console.log(v))

The issue you're running into is because the top level keys you're using are unique.您遇到的问题是因为您使用的顶级键是唯一的。 Instead of naming your keys Audi , BMW , etc. I would use a common key like make and set its value to your brands.而不是将您的钥匙命名为AudiBMW等。我会使用一个通用的钥匙,例如make并将其值设置为您的品牌。 That way, when you do a loop, you can ask for the same key every time:这样,当您执行循环时,您可以每次都请求相同的密钥:

const carBrands = [
  {
    make: 'Audi',
    models: ["A1", "A2", "A3", "A4"],
    unitsAvailable: 378
  },
  {
    make: 'BMW',
    models: ["M1", "M2", "M3", "M4"],
    unitsAvailable: 413
  },
];

carBrands.forEach(brand => {
    console.log(brand.make);

    brand.models.forEach(model => console.log(model));

});

Since you talked about wanting to maintain relationships in your object, I'd encourage you to think about how you would store this information in a database, and base your organization on that.既然您谈到要维护对象中的关系,我鼓励您考虑如何将这些信息存储在数据库中,并以此为基础构建您的组织。

There are many carBrands .有很多carBrands Each carBrand has a make , unitsAvailable , and has many models .每个carBrand都有一个makeunitsAvailable和许多models

You wouldn't make a new table for each carBrand , right?你不会为每个carBrand制作一个新表,对吧? You would add a new row.您将添加一个新行。 So, structuring it the way it is above is a closer parallel to how you would keep it in a database, which is good for data integrity and makes it more flexible.因此,按照上面的方式构建它更接近于将它保存在数据库中的方式,这有利于数据完整性并使其更加灵活。

In this structure, it's still easy to get things by make, too, like:在这种结构中,通过 make 获取东西仍然很容易,例如:

let audiModels = carBrands.filter(brand => brand.make == 'Audi').models;

Because your array consists of dict objects, you need to take into account that you need to iterate over the keys.因为您的数组由 dict 对象组成,所以您需要考虑到您需要遍历键。 Without modifying your input, you can use following code to address the inner values of your data structure:在不修改输入的情况下,您可以使用以下代码来处理数据结构的内部值:

// For all defined objects
carBrands.forEach((object) => {
  // Determine manufacturers inside the current object (only 1 manufacturer per object in your case)
  var manufacturers = Object.keys(object);
  // For each manufacturer
  manufacturers.forEach((manufacturer) => {
    // Print manufacturer name
    console.log("Manufacturer: " + manufacturer);
    console.log("Models:");
    // For all models
    var models = object[manufacturer].models;
    models.forEach((model) => {
      // print model name
      console.log("  " + model);
    });
    // print available units
    console.log("Available units:");
    console.log("  " + object[manufacturer].unitsAvailable + "\n");
  });
});

Output:输出:

Manufacturer: Audi
Models:
  A1
  A2
  A3
  A4
Available units:
  378

Manufacturer: BMW
Models:
  M1
  M2
  M3
  M4
Available units:
  413

Manufacturer: Honda
Models:
  H1
  H2
  H3
  H4
Available units:
  226

All answers here are "correct", thanks very much guys!这里的所有答案都是“正确的”,非常感谢大家! So there is not one to pick as better than the other.所以没有一个比另一个更好。

I think Jonathan makes a good point about my overcomplicated data structure.我认为 Jonathan 对我过于复杂的数据结构提出了一个很好的观点。 I will go back to the simpler versions where "Audi" etc would be a value, not a key.我将回到更简单的版本,其中“奥迪”等将是一个值,而不是一个键。

But I will also build a sample of the current structure and access data as suggested by Mottek.但我也会按照 Mottek 的建议构建当前结构的示例并访问数据。

When I get deeper into the project I will decide which will be the final version.当我深入研究该项目时,我将决定哪个是最终版本。

Thanks for the great help all!感谢大家的大力帮助!

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

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