javascript - 如何使用字符串访问嵌套对象值以便我可以编辑?
问题描述
如果我有以下字符串或数组:
var thestring = '[0]["more"][0]["more"][0]["text"]';
var thearray = ['0','more','0','more','0','text'];
如何使用该字符串或数组来识别对象的一部分以便可以编辑它?
var theobject = [
{
"id":1,
"text":"hello",
"more": [
{
"id":2,
"text":"hello",
"more":[
{
"id":3,
"text":"hello", // I want to edit this
"more": [
{
"id":4,
"text":"hello",
"more":[
]
}
]
}
]
}
]
},
{
"id":5,
"text":"hello"
},
{
"id":6,
"text":"hello"
},
{
"id":7,
"text":"hello"
}
];
基本上我正在尝试访问对象的这一部分:
theobject[0]["more"][0]["more"][0]["text"];
但是如果我用一个字符串来做它就行不通了:
theobject[thestring];
解决方案
查看 lodash _.get 和 _.set 函数,它们允许您使用路径类型语法访问对象,例如
_.get(object, 'property1.property2.property3', defaultValue);
存在等效的 _.set 函数,它们都很有用。
来自 lodash 文档:
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.get(object, 'a[0].b.c');
_.get(object, ['a', '0', 'b', 'c']);
_.get(object, 'a.b.c', 'default');
提供默认对象的能力也很不错,它使访问深度下一个对象变得非常容易。
Set 以类似的方式工作:
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.set(object, 'a[0].b.c', 4);
console.log(object.a[0].b.c);
// => 4
_.set(object, ['x', '0', 'y', 'z'], 5);
console.log(object.x[0].y.z);
// => 5
推荐阅读
- python - 如何使用熊猫搜索字符串模式并打印列中的总值
- bluetooth - Zephyr BLE:一个 GATT 客户端可以连接到多个 GATT 服务器吗
- python - 从 Matplotlib/Seaborn 箱线图中识别的数据集中删除异常值
- ansible - Jinja2 模板的结果在 Ansible 中以字符串形式返回
- javascript - 带有 typescript web 组件的 Oracle-jet
- ghostscript - Ghostscript PDF 到裁剪的 TIFF
- javascript - 如何通过布尔值数组过滤js对象数组
- python - 猴子补丁熊猫:在导入时修改 value_counts 函数
- sql - Postgres:在我使用聚合函数时必须出现在 GROUP BY
- html - 为什么 3d 图像立方体需要背景?