У меня есть сложный Объект
{
"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;
}, {});
}
и здесь песочница для игры с