【发布时间】:2020-01-17 15:43:16
【问题描述】:
我有一个复杂的对象
{
"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;
}, {});
}
【问题讨论】:
标签: javascript arrays object lodash