javascript - Lodash 从深度数组中挑选
问题描述
我有一个复杂的对象
{
"a": 1,
"b": {"test": {
"b1": 'b1'
}},
"c": {
"d": [{foo: 1}, {foo: 2}, {foo: 3, bar: 1}, {bar: 12}]
},
}
我有钥匙列表:
[
"a",
"b.test.b1",
"c.d[].foo"
]
我想要做的 - 是选择我有键的所有值。问题是 - 我不知道如何处理数组("c.d[].foo"
)。我不知道数组有多长以及哪些元素有或没有foo
结果应该是
{
"a": 1,
"b": {"test": {
"b1": 'b1'
}},
"c": {
"d": [{foo: 1}, {foo: 2}, {foo: 3}]
},
}
UPD 如果有人感兴趣,这是我对这个函数的实现:
const deepPick = (input, paths) => {
return paths.reduce((result, path) => {
if(path.indexOf('[]') !== -1) {
if(path.match(/\[\]/g).length !== 1) {
throw new Error(`Multiplie [] is not supported!`);
}
const [head, tail] = path.split('[]');
const array = (get(input, head) || []).reduce((result, item) => {
// if tail is an empty string, we have to return the head value;
if(tail === '') {
return get(input, head);
}
const value = get(item, tail);
if(!isNil(value)) {
result.push(set({} , tail, value));
} else {
result.push(undefined);
}
return result;
}, []);
const existingArray = get(result, head);
if((existingArray || []).length > 0) {
existingArray.forEach((_, i) => {
if(!isNil(get(array[i], tail))) {
set(existingArray, `${i}.${tail}`, get(array[i], tail));
}
});
} else if(array.length > 0) {
set(result, head, array);
}
} else {
set(result, path, get(input, path));
}
return result;
}, {});
}
这里有一个沙盒可以玩
解决方案
map-factory
可能有助于以优雅的方式完成这项任务。有关更多详细信息,请参见此处:https ://www.npmjs.com/package/map-factory
代码看起来像这样
const mapper = require("map-factory")();
mapper
.map("a")
.map("b.test.b1")
.map("c.d[].foo");
const input = {
a: 1,
b: {
test: {
b1: "b1"
}
},
c: {
d: [{ foo: 1 }, { foo: 2 }, { foo: 3, bar: 1 }, { bar: 12 }]
}
};
console.log(JSON.stringify(mapper.execute(input)));
推荐阅读
- macos - 尝试在 MAC 上使用 sed 编辑器交换 JSON 元素
- django - 到期后,令牌不起作用,api 抛出“未经授权的错误”
- azure - Azure function-Timer unscheduledInvocationReason
- ios - 您如何修改使用本机摄像头的 cordova 插件,以便尊重 iPhone X 上的安全区域?
- batch-processing - 了解在 DBOW 的单个时期发生了什么
- javascript - 状态更改后子组件不更新
- android - Android 应用程序链接 - 将网站与多个应用程序关联时的消歧对话框问题
- spring-boot - 为什么我在使用 mapstruct 从 DTO 映射到实体时没有得到 id?
- amazon-web-services - 带有 Internet 网关的 VPC 中的 AWS Lambda 函数仍然无法访问 Internet
- javascript - 为什么我会收到“UnhandledPromiseRejectionWarning”?