Kabe
Kabe

Reputation: 23

Creating dynamic objects with Javascript

I'm trying to create a new Javascript object from attributes pulled from the DOM using jQuery. The info I'm trying to pull is the data-* from this:

    <button type='button' class='pickup' data-name="apple" data-weight='1' data-color='red'>food</button>

So I want to get data-name and data-weight and put them into a new (or existing if I have to) object. Here's where I'm having problems. I want the object to look like this:

    MyObject = {
                food:  {
                        weight: 1,
                        color: 'red'
                       }
                }

I've been trying to create a new object like this through a "for(var i in MyObject)" loop, but when it comes down to adding the attributes and values to MyObject{} I can't figure out how to make it work.

Any ideas or suggestions?


The answers below worked perfectly! Thank you! How if I wanted to dynamically create:

    MyObject.food = {} 

from a variable, like this:

    var Name = "meal";
    MyObject.Name = {} // creates MyObject.meal = {};

How would I do that? I thought MyObject[Name] = {} would work but it didnt seem to for me. Maybe I typed it wrong? :S

Upvotes: 2

Views: 5421

Answers (4)

Rene Berwanger
Rene Berwanger

Reputation: 157

var FinalObject= {}
$('.filter-products select').each(function() {
   var property= $(this).attr('id');
   var value = $(this).val();
   FinalObject[property] = value;
});

console.log(FinalObject);

Upvotes: 1

tonny zhang
tonny zhang

Reputation: 1

You can use jQuery like this

var d = $(".pickup").data();

"d" is a Object with attributes of $('.pickup') start with 'data-',then you can use it hope it can help you!

Upvotes: 0

user1106925
user1106925

Reputation:

If you don't know what the attributes will be, you could loop the .attributes object.

var attrs = $('.pickup')[0].attributes;  // grab the attributes of the element

var MyObject = {  // create the object
    food: {}
};

  // loop the attributes, and add the data- attributes to the object
$.each(attrs, function(_, v) {
    if (v.name.indexOf('data-') !== -1)
        MyObject.food[v.name.replace('data-', '')] = v.value;
});

http://jsfiddle.net/5m7KF/


In HTML5 compliant browsers, you could use the .dataset property of the element to get the data- attributes.

var data = $('.pickup')[0].dataset;  

var MyObject = {  
    food: {}
};

$.each(data, function(k, v) {
    MyObject.food[k] = v;
});

http://jsfiddle.net/5m7KF/1/

Upvotes: 4

Christopher
Christopher

Reputation: 10647

$(".pickup").data("name") will fetch you "apple", etc.

Complete-ish example off the top of my head.

$(".pickup").click(function(){
    MyObject = {
        food:  {
            weight: $(this).data("weight"),
            color: $(this).data("color")
        }
    }
});

Upvotes: 0

Related Questions