Search code examples
javascriptember.jsember-data

how to build labels from the object key


I have a model that returns an object like this:

{type:"Fiat", model:"500", color:"white"}
{type:"ford", model:"f250", color:"green"}

I need create a label from the object keys for example type, model, color and a column that contains fiat, 500 etc. I was trying to use:

model.map(elem=>{ Object.keys(elem)}

to get the keys but I am getting the keys of each item in the object. Is there any way to get the key value?


Solution

  • the output should be label1 = type, label2=model, label3 = color

    if you want to name them by label + nth

    you can map over your cars then construct an object by looping over all the keys in a object.

    if i have misunderstood please leave a comment and i'd be happy to change. :)

    const cars = [{
        type: "Fiat",
        model: "500",
        color: "white"
      },
      {
        type: "ford",
        model: "f250",
        color: "green"
      }
    ]
    
    
    function getLabelsFromObject(model) {
      return Object.values(model).reduce(createLabelModel, {})
    }
    
    function createLabelModel(labels, label, i) {
      return Object.assign(labels, {[`label${i}`]: label})
    }
    
    console.log(cars.map(getLabelsFromObject))