简体   繁体   中英

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?

You can use a for...in loop to get each key in the Object , and then check for the existence of the string or character.

In the example below, I am checking to see that the key starts with the "~" character.

for (const key in myObject) {
    if (key.indexOf('~') === 0) {
        // key contains '~' character
    }
}

you could also use regex to match a string, instead of using indexOf

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 ~");
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM