根据formater(String类型)解构数组,返回对应字符的值,无对应值返回undefined
const parse = (str) =>
JSON.parse(str.replace(/([\d\w]{1,})/g, (subStr) => `"${subStr}"`));
function destructuringArray(array, formater) {
function fn(value, key, result) {
if (Array.isArray(key)) {
let newResult = { ...result };
key.forEach((item, index) => {
newResult = fn(value?value[index]:undefined, item, newResult);
});
return newResult;
}
return {
...result,
[key]: value
};
}
return fn(array, parse(formater), {});
}
console.log(destructuringArray([1, 2], "[a,b]"));
// {a: 1, b: 2}
console.log(destructuringArray([1, [2, 4], 5], "[a,[b],c,d]"));
// {a: 1, b: 2, c: 5, d: undefined}
console.log(destructuringArray([1, [2, 4], 5], "[a,[b],c,[d]]"));
// {a: 1, b: 2, c: 5, d: undefined}
console.log(
destructuringArray(
[1, [2, [4, [5], 10]], 6, 7, [8, 9]],
"[a,[b,[c,[d],x]],e,f,[g,h]]"
)
);
// {a: 1, b: 2, c: 4, d: 5, x: 10, e: 6, f: 7, g: 8, h: 9}