Search code examples
javascriptkeyobject-literal

check the name of an object literal property


I have a shorthand function for element creation that takes a tag name and an object literal.

//create element
function $make(tag, parameters) {
    var o = document.createElement(t);
    if (p.style) o.style.cssText = p.style;
    if (p.class) o.className = p.class;
    if (p.text) o.textContent = p.text;
    return o;
}

You call it simply enough:

var e = $make('div', {style: 'float: left', class: 'myClass', text: 'Some Text'});

Instead of setting a check for each individual attribute, I'd like to set attributes using a key character prefix in the property. For instance, if I wanted to set href for a link, I might call:

var e = $make('a', {style: 'float: left', text: 'Google', ~href: 'https://www.google.com'});

How can I iterate through the properties of an object literal and check whether the name of the property itself (not the value) starts with a specific character or string? Is this even possible? If not, what would you recommend as an alternative?


Solution

  • Instead of for...in I'd suggest using a forEach loop over the Object.keys function. This is because for ... in looks up the prototype chain (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#Iterating_over_own_properties_only).

    var obj = {"style": 'float: left', "text": 'Google', "~href": 'https://www.google.com'};
    Object.keys(obj).forEach((elm) => {
      console.log("Key=>Value : " + elm + "=>" + obj[elm]);
      if(elm.contains("~")) {
        console.log("Key: " + elm + " contains ~");
      }
    });