[英]Edit a deep part of an object with string key with dots
i need to merge two objects, where one is a part with some changes of an old one.我需要合并两个对象,其中一个是对旧对象进行一些更改的一部分。
So, we have an object that looks like this (example):所以,我们有一个 object 看起来像这样(示例):
{
"item": {
"data": "some text here",
"info": {
"test": {
"roles": [
"admin"
],
"index": 0
}
}
}
}
and then we have a string that looks like this: "item.info.test"
and also we have a new object, that is actually a part of an old one.然后我们有一个看起来像这样的字符串:
"item.info.test"
,我们还有一个新的 object,它实际上是旧字符串的一部分。
{
"roles": [
"admin"
],
"index": 5
}
how can we replace last subkey with a new object?我们如何用新的 object 替换最后一个子项?
i tried using obj[key][subkey] etc, but its impossible to do this with lots of keys.我试过使用 obj[key][subkey] 等,但是用很多键是不可能的。
If you only need to deal with object keys not with array indexes, you could do something like this:如果你只需要处理 object 键而不是数组索引,你可以这样做:
const data = { "item": { "data": "some text here", "info": { "test": { "roles": [ "admin" ], "index": 0 } } } } const path = 'item.info.test'; const replacement = { "roles": [ "admin" ], "index": 5 }; const pathArray = path.split('.'); const lastKey = pathArray.pop(); const penultimate = pathArray.reduce((a, c) => a[c], data); penultimate[lastKey] = replacement; console.log(data);
This approach mutates the original object ( data
) and I've probably made it more complicated then it has to be.这种方法改变了原来的 object (
data
),我可能让它变得比它必须的更复杂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.