Search code examples
javascriptarrayshandlebars.jsunderscore.js

convert array values to object, add keys based on index position


I'm using a data source in a handlebars template. When I fetch the data the resulting object contains nested arrays like:

["10004", "Some title", "Some Description", "$19.95", "Some other text here..."]

I want to convert the array values to objects and set/access the object keys (this is for inclusion on handlebars template). any advice helpful. ty!

for more info: this is what I have constructed so far.

// data from API http response is var data

let dataObj = {};
    dataObj =
      _.chain(data)
      .values()
      .map(function(el){
        return {'product': el};
      });

my result is like so:

{"products": [
     {
         "product":[
            "123456",
            "Some title",
            "Some descritpion.Lorem ipsum"
         ]
      }
]};

but what I'm looking for is:

{
   "products":[
      {
         "product":[
            {
               "id":"123456"
            },
            {
               "title":"Some title"
            },
            {
               "description":"Some descritpion.Lorem ipsum"
            },
            {
               "price":"$103.05"
            }
         ]
      }
   ]
}

edit: thanks again for dropping by!


Solution

  • In this case, you can create a simple convert function and reuse it.

    function convert(data){
           return {
              product: [{
                 id: data[0],
                 title: data[1],
                 description: data[2],
                 price: data[3]
              }]
           }
        }
    

    let data = ["10004", "Some title", "Some Description", "$19.95", "Some other text here..."];
    
    function convert(data){
       return {
          product: [{
             id: data[0],
             title: data[1],
             description: data[2],
             price: data[3]
          }]
       }
    }
    
    console.log(convert(data))