3

I'm trying to get the class name from an HTML div elements and add it to an existing object. What's maddening is that I can make it work, but every syntax error checker I put it into says the code is wrong. I've searched pretty thoroughly, but I don't even know how to phrase the question, really. Here's the code which DOESN'T throw the error:

$.each( $(objDiv).children('div'), function(){
    var field = $(this).attr('class');
    var value = $(this).text();
    var add = { field : value };
    $.extend(obj, add);
});

But the problem is that it puts "field" in as a literal string for the field

object {label: "level3a", field: "Authoritatively enhance client-centric deliverables after sustainable expertise."}

object {label: "level3a", field: "Completely embrace clicks-and-mortar data without ubiquitous meta-services."}

not the class name value. To get around that, I put brackets around "field":

$.each( $(objDiv).children('div'), function(){
    var field = $(this).attr('class');
    var value = $(this).text();
    var add = { [field] : value };
    $.extend(obj, add);
}

And it gives me the result I'm looking for,

object {label: "level3a", ClassA: "Authoritatively enhance client-centric deliverables after sustainable expertise."}

object {label: "level3a", ClassB: "Completely embrace clicks-and-mortar data without ubiquitous meta-services."}

but somehow it's incorrect. Any ideas on what I'm doing wrong here, or a better way to accomplish this?

1 Answers1

3

While I can't tell you why that's wrong (or why it works, for that matter), I can tell you a more "proper" way to do it.

You'd declare add as an empty object like so: add = {};

Then you can add the field as a property to it like so: add[field] = value;

This will give you an object add with the model: { ClassA: "Your text here" }

Please refer to the types of property accessors for more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors. The method detailed above uses "Bracket Notation"

Edit: So apparently in ECMA6 what you wrote is valid javascript, using what's called a ComputedPropertyName. However it's not supported by all browsers yet, so until browser support for ECMA6 gets better you're better off using the bracket-notation property name method. See this answer for more info: https://stackoverflow.com/a/2274327/2748503

Community
  • 1
  • 1
Redmega
  • 673
  • 5
  • 21