0

If I have some values and I want to store it as an object. So finally I need to call JSON.stringify() (because I am trying to store it in chrome extension)

var id = '1';
var name = 'Mali Bakery'
var url = 'http://example.com/'

So I thought the best thing would be sorting it like:

var items = {
     id : {
        'name': name,
        'url': url
     }
}

But I couldn't figure out how to put the variables inside the object template.

I tried using

item = {}
item[id] = id
item[id].name = name  
// etc

items.push(item);

// and also, this approach too
items.id = id

But no success.

senty
  • 11,415
  • 25
  • 114
  • 244

4 Answers4

2

You can put id in brackets [] so that it gets evaluated to the variables value:

var id = '1';
var name = 'Mali Bakery'
var url = 'http://example.com/'

var items = {
      [id] : {
        name,
        url
     }
}

console.log(items);

Note that you shouldn't use name as a variable's name!

baao
  • 67,185
  • 15
  • 124
  • 181
2

You could do this

var id = '1';
var name = 'Mali Bakery'
var url = 'http://example.com/'
var items = {}

items[id] = {
    'name': name,
    'url': url
}

console.log(items);

This gives the following output:

{ 1:{ name: "Mali Bakery", url: "http://example.com/" } }

lordvcs
  • 1,657
  • 2
  • 24
  • 33
1
var items = {};
items[id] = { name, url };
ideaboxer
  • 3,513
  • 8
  • 40
  • 58
1
    var id = '1';
    var name = 'Mali Bakery'
    var url = 'http://example.com/'

    var obj = {
            'name': name,
            'url': url
         }

    var items = {};

    items[id] = obj;
Prakash Sharma
  • 13,640
  • 3
  • 28
  • 35