The following works but I'm trying to find a way to omit the arrayOfObjects[1]['testParent'] = {}
bit, imagine you wanted to add a value to an empty object that is nested 10 levels down, you would have to initialize each level with an empty {}
first, I'm trying to find a workaround for that.
let arrayOfObjects = [ {}, {}, {}, ] arrayOfObjects[1]['testParent'] = {} arrayOfObjects[1]['testParent']['testKey'] = 'testValue' // is there a way to do the above in one line, without having to initialize testParent with an empty object on line 7? console.log(arrayOfObjects)
arrayOfObjects[1] = {
testParent: {
testKey: 'testValue'
}
};
In fact, you can avoid the array indexer as well with something like:
arrayOfObjects = [
{},
{
testParent: {
testKey: 'testValue'
}
},
{}
];
You can create custom method for this, using reduce
that takes string and value and sets nested property.
let arr = [{}, {}, {}] function set(obj, key, value) { key.split(".").reduce((r, e, i, a) => { return r[e] || (r[e] = a[i + 1] ? {} : value) }, obj); } set(arr, "0.testParent.testKey", "testValue") set(arr, "2.abf", "value") set(arr, "2.abc", "value") console.log(arr)
Maybe a small helper can help you to omit the brackets:
const $ = (obj, key, ...keys) => key != undefined ? $(obj[key] || (obj[key] = {}), ...keys) : obj;
Usable as:
const arr = [];
$(arr, 1, "testParent").testKey = "testValue";
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.