[英]Lodash _.flatMapDepth to return an array of objects deep level nested
i am trying to get an array from deep level nested structure, i was able to get one level.我试图从深层嵌套结构中获取一个数组,我能够得到一个级别。 Even if i pass depth as 4 also i am not able to get.
即使我将深度传递为 4,我也无法获得。
any help is appreciated任何帮助表示赞赏
input输入
let a = [{b: [{c: [{d: [{e: "name"}]}]}]}]
tried snippet试过的片段
let output = _.flatMapDepth(a, 'e', 3);
getting empty array获取空数组
i need to get as below, using lodash我需要得到如下,使用 lodash
output = [{e: "name"}]
any help is appreciated任何帮助表示赞赏
better use _().flatMap更好地使用 _().flatMap
let a = [{b: [{c: [{d: [{e: "name"}]}]}]}];
console.log(a);
let output1 = _(a).flatMap('b').flatMap('c').flatMap('d').value();
console.log(output1); // [ { e: 'name' } ]
let output2 = _(a).flatMap('b').flatMap('c').flatMap('d').flatMap('e').value();
console.log(output2); // [ 'name' ]
This one goes through the nested objects and resolves them!这个遍历嵌套对象并解析它们!
From the Lodash docs :来自Lodash 文档:
// _.flatMapDepth(collection, [iteratee=_.identity], [depth=1])
function duplicate(n) {
return [[[n, n]]];
}
_.flatMapDepth([1, 2], duplicate, 2);
// => [[1, 1], [2, 2]]
and _.identity和_.identity
// _.identity(value)
var object = { 'a': 1 };
console.log(_.identity(object) === object);
// => true
I think this should help.我认为这应该有所帮助。
If this does not help.如果这没有帮助。 I have written a JavaScript solution to your problem:
我已经为您的问题编写了一个 JavaScript 解决方案:
let a = [{ b: [{ c: [{ d: [{ e: "name" }] }] }] }, { b: [{ c: [{ d: [{ e: "age" }] }] }] }]; function getDeepKeys(arr, key, maxDepth = 8) { let res = []; let depth = 0; for (let i = 0; i < arr.length; i++) { const obj = arr[i]; if (typeof obj !== "object" || obj == null) { continue; } for (const k in obj) { if (obj.hasOwnProperty(k)) { const element = obj[k]; if (k === key) { res.push(obj); // can also be res.push(element) // if you want the contents of obj to be added to the resulting array continue; } else if (depth <= maxDepth) { res = getDeepKeys(element, key).concat(res); depth++; } } } } return res; } let keys = getDeepKeys(a, "e"); console.log(keys);
Be careful, though.不过要小心。 If there's an object without the
e
key, you will get an infinite loop error.如果有一个没有
e
键的对象,你会得到一个无限循环错误。 Therefor I created the depth
and maxDepth
variable.因此我创建了
depth
和maxDepth
变量。 You can adjust this value like so: getDeepKeys(a, "e", 12);
你可以像这样调整这个值:
getDeepKeys(a, "e", 12);
(now the maxDepth
equals 12 instead of the default value of 10). (现在
maxDepth
等于 12 而不是默认值 10)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.