【发布时间】:2023-03-31 15:50:01
【问题描述】:
我在使用 lodash 的 nodejs 应用程序中有一个树形数据结构:
var l = require("lodash");
obj_string =
`
[
{
"father_id": 1,
"name": "father 1",
"child_array": [
{
"id": 11,
"name": "father 1 child 1"
},
{
"id": 12,
"name": "father 1 child 2"
}
]
},
{
"father_id": 2,
"name": "father 2",
"child_array": [
{
"child_id": 21,
"name": "father 2 child 1"
},
{
"child_id": 22,
"name": "father 2 child 2 - TO DELETE"
}
]
}
]
`;
tree = JSON.parse(obj_string);
我想通过 id 移除一个孩子,但我不知道他的父亲是什么:
l.chain(tree).flatMap(f=>f.child_array).remove(c=>c.child_id==22);
它不起作用,为什么!?我使用了 java 流,但我不明白 lodash 是如何工作的。 例如,如果我想搜索一个孩子并且我想引用已创建的孩子,例如为了编辑它的成员(没有 _.map),我该怎么做?
有了这个:
ret = l.chain(tree).flatMap(f=>f.child_array).find(c=>c.child_id==22).value();
我在 ret 中有一个新对象,所以我无法访问/编辑原始对象。 换句话说,第二个问题是:如何从 lodash 包装器中检索对象引用?
【问题讨论】:
-
也许你可以试试highlandjs.org 它可以让你使用流和背压
-
我看看,谢谢
-
@Salvo 你是从字符串中解析的吗?然后您必须更新已解析的(原始)对象(删除带有 id
的子对象)?那么有更好的解决方案!
标签: javascript arrays node.js stream lodash