Languages
[Edit]
DE

JavaScript - einen Wert für den Deskriptor verschachtelter Schlüsselzeichenfolgen in einem Objekt festlegen

3 points
Created by:
Nikki
1620

In diesem Artikel wird gezeigt, wie ein Wert f├╝r den Deskriptor verschachtelter Schl├╝sselzeichenfolgen in einem Objekt mithilfe eines modernen ECMA - Skripts (modernes JavaScript) festgelegt wird:

Beispiell├Âsung:

// ONLINE-RUNNER:browser;

const setNestedProperty = (object, path, value) => {
    if (path.length == 0) {
        return;
    }
    const limit = path.length - 1; 
    for (let i = 0; i < limit; ++i) {
        const name = path[i];
        object = object[name] || (object[name] = { });
    }
    const name = path[limit];
    object[name] = value;
}

// Usage example:

const object = {
    name: 'John',
    metadata: {
        type: 'json'
    }
};
const myKeyPath = ['metadata', 'key'];
const myKeyValue = 'my-key-value';

setNestedProperty(object, myKeyPath, myKeyValue);
console.log(`object.metadata.key='${object.metadata.key}'`);

 

Hey ­čĹő
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.