Created
October 26, 2022 15:21
-
-
Save buglss/935d4c2a577a8e853656e3b3575c19d4 to your computer and use it in GitHub Desktop.
[EN] It is a function that assigns the specified value to a nested object according to the specified path. If the object is not sent as a parameter, a new object is created and returned. [TR] Belirtilen değeri belirtilen path'e göre nested bir objede atama yapan fonksiyondur. Eğer parametre olarak obje gönderilmezse yeni bir obje oluşturup döndü…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* * STRUCTURE [EN] | |
* - .: Character used to separate the path of Keys/Fields. (key.key.key...) | |
* | |
* * YAPI [TR] | |
* - .: Anahtarların/Alanların yolunu ayırmak için kullanılan karakter. (key.key.key...) | |
* | |
* * USAGE EXAMPLE / KULLANIM ÖRNEĞİ | |
* setByPathOfObject("document.customField.meta.value", 28) | |
* => { document: { customField: { meta: { value: 28 } } } } | |
**/ | |
function setByPathOfObject(path, value, obj = {}) { | |
let pathArray = path.split(".") | |
if(pathArray.length === 0) return obj = value | |
let stopAt = pathArray.length - 1 | |
pathArray.reduce((obj, key, i) => { | |
if(i === stopAt) { | |
if(typeof obj === "object") obj[key] = value | |
else obj = { [key]: value } | |
} else { | |
obj[key] = typeof obj[key] === "object" ? obj[key] : {} | |
} | |
return obj[key] | |
}, obj) | |
return obj | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment