Home > Mobile >  Create a table with keys and values from JS map
Create a table with keys and values from JS map

Time:05-26

I'm trying to create a table with all its information from a javascript map (it's for a school project, if you're wondering why I have to use map). This feels like it shouldn't be a problem but my brain refuses to cooperate.

        var volkswagen = {
            name: "Volkswagen",
            country: "Germany",
            revenue: 260000000000
        };

        var toyota = {
            name: "Toyota",
            country: "Japan",
            revenue: 256000000000
        };

        var mercedes = {
            name: "Mercedes",
            country: "Germany",
            revenue: 187000000000
        };

        var brands = new Map();
        brands.set(volkswagen.name, volkswagen);
        brands.set(toyota.name, toyota);
        brands.set(mercedes.name, mercedes);

How would one go about doing this?

CodePudding user response:

if i undrastend you want to fill brands table with objects so try this :

var brands = []
brands.push(volkswagen)
brands.push(toyota)
etc...
 or 
var brands = [volkswagen,toyota etc...]

CodePudding user response:

There are many possible ways of compiling a table out of the data you provided, the following is one of them:

var volkswagen = {
  name: "Volkswagen",
  country: "Germany",
  revenue: 260000000000
};

var toyota = {
  name: "Toyota",
  country: "Japan",
  revenue: 256000000000
};

var mercedes = {
  name: "Mercedes",
  country: "Germany",
  revenue: 187000000000
};

document.body.innerHTML=
`<table><tr><th>${Object.keys(toyota).join("</th><th>")}</th></tr>
${[volkswagen,toyota,mercedes].map(o=>
    "<tr><td>" Object.values(o).join("</td><td>") "</tr>").join("\n")}</table>`
td,th {border:1px solid grey}

  • Related