7

ワイルドカードに基づいてjavascriptオブジェクトからプロパティを動的に削除する改善された方法に興味があります。まず、次のオブジェクトがあるとします。

object =
{
    checkbox_description_1 : 'Chatoyant',
    checkbox_description_2 : 'Desultory',
    random_property : 'Firefly is a great program',
    checkbox_mood_1 : 'Efflorescent',
    checkbox_description_3 : 'Ephemeral'
}

タスク

これで、最終結果は、「checkbox_description」を装ってすべてのプロパティを削除し、次のようにオブジェクトの残りの部分をそのまま残します。

object =
{
    random_property : 'Firefly is a great program',
    checkbox_mood_1 : 'Efflorescent',
}

私の解決策

現在、私のソリューションにはjqueryと次のコードが含まれています。

var strKeyToDelete = 'checkbox_description'

/* Start looping through the object */
$.each(object, function(strKey, strValue) {

    /* Check if the key starts with the wildcard key to delete */
    if(this.match("^"+strKey) == strKeyToDelete) {

        /* Kill... */
        delete object[strKey];
    };
});

問題

これについての何かは私には非常にエレガントではないように思われ、オブジェクトが妥当なサイズである場合、非常にプロセス集約的です。この操作を実行するためのより良い方法はありますか?

4

4 に答える 4

9

これは最低限必要なものです。

function deleteFromObject(keyPart, obj){
    for (var k in obj){          // Loop through the object
        if(~k.indexOf(keyPart)){ // If the current key contains the string we're looking for
            delete obj[k];       // Delete obj[key];
        }
    }
}

var myObject = {
    checkbox_description_1 : 'Chatoyant',
    checkbox_description_2 : 'Desultory',
    random_property : 'Firefly is a great program',
    checkbox_mood_1 : 'Efflorescent',
    checkbox_description_3 : 'Ephemeral'
};
deleteFromObject('checkbox_description', myObject);
console.log(myObject);
// myObject is now: {random_property: "Firefly is a great program", checkbox_mood_1: "Efflorescent"};

つまり、これはあなたが持っているjQuery関数にかなり近いものです。
(少し速いですが、jQueryを使用していないことを考えると、indexOf代わりにmatch

それで、~以前はindexOfどうですか?

indexOf文字列が見つからない場合は整数値を返し、-1見つかった場合は。から始まるインデックスを返します0。(したがって、見つかった場合は常に正の整数)
~はビット単位NOTであり、この出力を反転します。たまたま、の反転出力は、indexOf「見つかった」または「見つからなかった」を示すために必要なものです。

~-10、偽りの値になります。
~xxis0またはpostitiveは-(x+1)、真の値になります。

このように、JavaScriptにはない関数の~string.indexOf('needle')ように機能します。string.contains('needle')

!!さらに、の前に二重ブール値not()を追加して~、true-ishまたはfalse-ishの出力を実際のtrue / falseに変換できますが、JavaScriptでは必要ありません。
機能的に、~string.indexOf('needle')そして!!~string.indexOf('needle')等しい。


針から始めるために特にキーが必要な場合は、次のものを交換してください。

~k.indexOf(keyPart)

と:

k.indexOf(keyPart) === 0
于 2012-12-14T08:55:33.387 に答える
4
    var myObject = {
        checkbox_description_1 : 'Chatoyant',
        checkbox_description_2 : 'Desultory',
        random_property : 'Firefly is a great program',
        checkbox_mood_1 : 'Efflorescent',
        checkbox_description_3 : 'Ephemeral'
   };

const removeProperty = dyProps => ({ [dyProps]: _, ...rest }) => rest;

const remove_random_property = removeProperty('random_property');
console.log(remove_random_property(myObject));
于 2019-03-18T17:44:31.150 に答える
3

文字列「StartsWith」が別の文字列であるかどうかを確認する方法を使用できますか?:

function deleteFromObject(keyToDelete, obj) {
    var l = keyToDelete.length;
    for (var key in obj)
        if (key.substr(0, l) == keyToDelete) // key begins with the keyToDelete
            delete obj[key];
}
于 2012-12-14T11:29:43.313 に答える
0

元のオブジェクトを変更しないソリューションを探している場合は、次のような方法を試すことができます

const omit = (source = {}, omitKeys = []) => (
  Object.keys(source).reduce((output, key) => (
    omitKeys.includes(key) ? output : {...output, [key]: source[key]}
  ), {})
)

テスト

const original = {a:1, b:2, c:3, d:4, e:5}
console.log('original: ', JSON.stringify(original));

const modified = omit(original, ['b', 'd'])
console.log('modified: ', JSON.stringify(modified));
console.log('original: ', JSON.stringify(original));

// Will log: 
// original: {"a":1,"b":2,"c":3,"d":4,"e":5}
// modified: {"a":1,"c":3,"e":5}
// original: {"a":1,"b":2,"c":3,"d":4,"e":5}

これにより、新しいオブジェクトが作成され、例外リスト(omitKeys)に含まれているものを除いて、ソースオブジェクトのすべてのプロパティがそのオブジェクトに拡散されます。

于 2021-08-10T00:05:11.857 に答える