【问题标题】:Lodash - find value in nested ObjectsLodash - 在嵌套对象中查找值
【发布时间】:2020-01-22 20:10:30
【问题描述】:
我有一个如下链接中提到的对象结构
https://jsonblob.com/3511b867-dd4b-11e9-85e4-63b804994c26
我想使用lodash在persons下的所有节点中搜索firstname: Dianca。
我不想对节点名称进行硬编码,因为我提到了很多要查找的节点。我需要在 person 节点下动态搜索它,无论它位于 Object 结构下的什么位置。
我尝试了如下方法,但徒劳无功(比如硬编码的东西)
_.filter(users, o =>
_.some(o.Positions, ['persons.firstname', 'Dianca'])
)
其次,我想获取persons 节点下的所有名称并将其保存到新数组..
我们将不胜感激。
【问题讨论】:
标签:
javascript
arrays
object
lodash
【解决方案1】:
什么问题!我花了一年的时间为你建立一个逻辑:)
function findUser(data, firstName) {
var object;
data.some(function f(a) {
if (a.firstname == firstName) {
object = a;
return true;
}
_.each(Object.keys(a), function (value, key) {
// loops through json objects in waypath
if (!_.isEmpty(object)) {
return false; // stop once we get the user
}
if (isNaN(value)) {
// only data with string keys need to iterate more
// when there is an array with elements
if (Array.isArray(a[value]) && a[value].length != 0) {
a[value].some(f); // recursion (Didn't use return because we are in loop)
} else if (!_.isEmpty(a[value])) {
// when there is an object within object
_.each(Object.keys(a[value]), function (val, key2) {
if (Array.isArray(a[value][val]) && a[value][val].length != 0) {
a[value][val].some(f); // recursion
}
});
}
}
});
});
return object;
}
console.log(findUser(data, "Phyllis"));
应该正是您所需要的。享受!!