Article From:https://segmentfault.com/q/1010000012145622
Question:

The WeChat applet has a function requirement to transfer the string to the object. It can be implemented quickly by using the eval method.
This is probably the process.

    var name = 'bb[0]'; //name It is a variable, assuming that its value is'bb[0]', and the value that may also be passed is'aa[0] or bb[1]'.Var data = {"AA": [[111], "222"], "BB": [[333], "444"];The value of //data is fixedVar newData = Eval ('data.'+name); / / method 1The result of //console.log (newData) is 333VarJsonStr = JSON.stringify (data);Var newData = (New Function ("var temp =" + jsonStr + "; return)Temp.'+ name)) (); / / method 2The result of //console.log (newData) is 333

Later found that the original JS functions that were banned after updating the applet: new Function, Eval and Generator. That means the previous methods can’t be used.
In addition to the 2 above, what is the way to get the correct result of newData?

Answer 0:

Shouldn’t it be the _.at of lodash? Without making wheels, lodash is ready for you.

var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
 
_.at(object, ['a[0].b.c', 'a[1]']);
// => [3, 4]

Jab the official document _.at

Answer 1:

You can write this
hold var name = 'bb[0]';====> Through regular transformationvar test = ['bb', '0']

ThennewData = data[test[0]].test[1]

Answer 2:
function trans(data, name) {
    let reg = /\[?[^\[\]]+\]?/g
    let reg2 = /\]/
    let names = name.match(reg)
    if (names.length) {
        names = names.map(item => reg2.test(item) ? item.slice(1, -1) : item)
        return names.reduce((sum, cur) => sum[cur], data)
    }
}

var data = {"aa":["111","222"],"bb":["333","444"]};
var name = 'bb[0]';
trans(data, name)

Answer 3:
var data = {"aa":["111","222"],"bb":["333","444"]};
name = 'bb[0]';


function getNewData(data, name){
    var prefix = name.split('[')[0],
        endStr = name.split('[')[1];
    var index = endStr.split(']')[0];
    return data[prefix][index];
}

var newName =  getNewData(data, name);
console.log(newName); // 333

Answer 4:
data['bb']['0']

Answer 5:

A regular match is all right

        function aaa(json,str){
                var b =  str.replace(/(\S)\[([0-9]+)\]/,'$1,$2').split(',');
                return json[b[0]][b[1]];
            }
            var newData = aaa(data,name); 
            console.log(newData);

Leave a Reply

Your email address will not be published. Required fields are marked *