1

How can I make an object dynamically in Javascript ?

What I Expect

var tree_data = {
    'for-sale' : {name: 'For Sale', type: 'folder'} ,
    'vehicles' : {name: 'Vehicles', type: 'folder'} ,
    'rentals' : {name: 'Rentals', type: 'folder'}   ,
    'real-estate' : {name: 'Real Estate', type: 'folder'}   ,
    'pets' : {name: 'Pets', type: 'folder'} ,
    'tickets' : {name: 'Tickets', type: 'item'} ,
    'services' : {name: 'Services', type: 'item'}   ,
    'personals' : {name: 'Personals', type: 'item'}
}

My Try

// Here I remove all white space from my string 
var nome = result[indice].Texto.replace(/ /g, '');

// Here I create the item
var novoMenu = {
      pasta: {
           name: result[indice].Texto,
           type: "folder"
      }
}

// and then fill my object
self.tree_data.push(novoMenu);

But this way my tree_data object becomes like

{ 
   pasta: {
         name: "For Sale',
         type: 'Folder'
   }
}

pasta should be the name without whitespace. How can I do this in Javascript?

JJJ
  • 32,902
  • 20
  • 89
  • 102
Lucas_Santos
  • 4,638
  • 17
  • 71
  • 118

2 Answers2

1

tree_data is an object, not an array. It should be initialized as:

self.tree_data = {};

Then your loop should add to it with:

self.tree_data[nome] = novoMenu;
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

You need to use the name as the index into the object:

// Here I remove all white space from my string 
var theName = result[indice].Texto.replace(/ /g, ''); //Shouldn't this be .replace(/ /g, '-') ?

// Here I create the item
var novoMenu = {};
novoMenu[ theName ] = {
           name: result[indice].Texto,
           type: "folder"
      }
};

// and then fill my json array
self.tree_data.push(novoMenu);
Don Rhummy
  • 24,730
  • 42
  • 175
  • 330