简体   繁体   English

如何实现类似解构赋值的功能?

[英]How to achieve a function similar to the deconstruction assignment?

How to achieve a function similar to the deconstruction assignment?如何实现类似解构赋值的功能?

const res = foo([1, [2,3], [4,5,[6,[7,8]]]], '[a, [b, c], [d, [e, [f]]]]')
// res = {a: 1, b: 2, c: 3, d: 4, e: 6, f: 7}

foo ?富? Thanks.谢谢。

Here's a solution based on这是一个基于的解决方案

  • a JSON parsing (with a trick) to build a structure from the second argument JSON 解析(使用技巧)以从第二个参数构建结构
  • a recursive parallel descent in both arrays, as hinted in my comment两个数组中的递归并行下降,如我的评论中所暗示的

 function foo(arr, desc){ var map = {}; (function dive(arr, struct){ struct.forEach((v, i) => { if (arr[i] === undefined) return; if (Array.isArray(v)) { dive(arr[i], v); } else { map[v] = arr[i]; } }); })(arr, JSON.parse(desc.replace(/\\w+/g, '"$&"'))); return map; } const res = foo([1, [2,3], [4, [6,[7,8]]]], '[a, [b, c], [d, [e, [f]]]]') // ^ I removed not matching data here console.log(res);

Note that it assumes the data matches the structure.请注意,它假定数据与结构匹配。 You'd better add error handling in the general case.在一般情况下,您最好添加错误处理。

My solution defers from the OP's original request, as it accepts an array of keys, and not string.我的解决方案推迟了 OP 的原始请求,因为它接受一组键,而不是字符串。 I think that it reflects the "similar to the deconstruction assignment" request better than a string.我认为它比字符串更好地反映了“类似于解构赋值”的要求。

This is a recursive solution that accepts an array of values, and an array of keys with the same shape, and uses Array.forEach() to iterate the keys, and extract the matching values.这是一个递归解决方案,它接受一组值和一组具有相同形状的键,并使用Array.forEach()迭代键,并提取匹配的值。

If you want to skip a value, use null as the key.如果要跳过某个值,请使用null作为键。

Note: You should add checks to ascertain that the shapes are similar, and throw errors/use defaults if they are different.注意:您应该添加检查以确定形状是否相似,如果它们不同,则抛出错误/使用默认值。

 const destructor = (values, keys) => { const obj = {}; const iterate = (values, keys) => keys.forEach((key, i) => { if(key === null) { return; } if(Array.isArray(key)) iterate(values[i], key) else obj[key] = values[i] }) iterate(values, keys) return obj; } const res = destructor([1, [2,3], [4,5,[6,[7,8]]]], ['a', ['b', 'c'], ['d', null, ['e', ['f']]]]) console.log(res)

Here's my version of this:这是我的版本:

function destructor(values, keys) {
    const output = {};
    const kReg = /(?:"([^"]+)"|'([^']+)'|(\w+))/g;
    keys = keys.replace(/\{[^{}]+\}/g, match => match.replace(kReg, '"$1$2$3":"$1$2$3"'));
    keys = keys.replace(kReg, '"$1$2$3"');

    keys = JSON.parse(keys);

    function forAll(array, func, loc) {
        loc = loc || [];

        if (typeof array === 'object') {
            const nest = Object.assign({}, array);
            for (let a in nest) {
                if ({}.hasOwnProperty.call(nest, a)) {
                    nest[a] = forAll(nest[a], func, loc.concat(a));
                }
            }

            return nest;
        } else {
            return func(array, loc);
        }
    }
    function nestedGet(values, path) {
        const key = path.shift();

        return key === undefined ? values : (
            typeof values[key] === 'undefined' ? 
            undefined : nestedGet(values[key], path)
        );
    }

    forAll(keys, (elem, path) => {
        output[elem] = nestedGet(values, path)
    });

    return output;
}

The key difference between this version and other versions is that you can also use {key1, key2} esq deconstructions.此版本与其他版本的主要区别在于您还可以使用{key1, key2} esq 解构。

For example:例如:

destructor(
     [1, [2, 3], [4, {e:5, f:6}]],
    '[a, [b, c], [d, {e,   f  }]]'
);

Becomes:变成:

{
    'a':1,
    'b':2,
    'c':3,
    'd':4,
    'e':5,
    'f':6
}

Your example:你的例子:

destructor(
     [1, [2, 3], [4, 5, [6, [7, 8]]]],
    '[a, [b, c], [d, [e, [f]]]]'
);

Becomes:变成:

{
    'a':1,
    'b':2,
    'c':3,
    'd':4,
    'e':undefined,
    'f':undefined
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM