如何根据字符串解析复杂对象和数组

时间:2019-01-19 10:26:10

标签: javascript parsing

我在变量 y 中有字符串,这类似于js中用于解析对象的普通解析方程,并且我在变量 x 中具有复杂的对象。现在,我想在名为 parser 的函数中传递变量,并且该函数应该从object返回我已解析的数据。如果您对我的问题不清楚,请看一下我的例子,您会很清楚。

var a = {data:{info:{name:'mina'},interested: ['programming','makeup']}}
function parse(x, y) { var y = y.split('.').reverse();
    for (var j = x, i = (y.length - 1); i >= 0; --i) { 
        j =  j !== undefined && j[y[i]] !== undefined ?j[y[i]] : false;
    }
    if (j) {
        return j;
    }
}
parse(a,'data.info.name') //output = mina
parse(a,'data.info')  //{name: "mina"}
parse(a,'data.interested[1]')

此函数最适合对象解析,但是我无法使用此函数解析数组,我正在寻找也可以解析数组的解决方案。请帮助我,我已尽力能够解析诸如 a.data.name [0] 之类的简单数组,但无法解析诸如 a.data.name [0]之类的复杂数组[0]。名称[0](示例)

请帮助我解决此问题

1 个答案:

答案 0 :(得分:0)

我认为这就是您想要的:

let a = {
  users: {
      user1: {
          name: 'Mina',
          interested: ['programming', 'makeup', 'get an answer'],
          complexArray: [['test1'], ['test2',{
              ultimateTest: ['success', 'more success']
          }]]
      },
      user2: {
          name: 'Ernesto',
          interested: ['give an answer']
      }
  }
};

function getContent(element, address) {

    let i, j;
    let x, y, z;
    let length1, length2;
    let currentPosition = element;

    address = address.split('.');
    length1 = address.length;

    for (i = 0; i < length1; i++) {
        x = address[i].match(/\[\d\]/g);
        if (x !== null) {
            // ARRAY TYPE ADDRESS
            y = address[i].replace(/\[\d\]/g, '');
            currentPosition = currentPosition[y];
            length2 = x.length;
            for (j = 0; j < length2; j++) {
                z = x[j].replace(/\D/g, '');
                z = parseInt(z);
                currentPosition = currentPosition[z];
            }
        } else {
            // OBJECT TYPE ADDRESS
            currentPosition = currentPosition[address[i]];
        }
    }

    return (currentPosition);

}

getContent(a, 'users.user1.interested[0]'); // OUTPUT: 'programming'
getContent(a, 'users.user2.name'); // OUTPUT: 'Ernesto'
getContent(a, 'users.user1.complexArray[1][1].ultimateTest[0]'); // OUTPUT: 'success'
getContent(a, 'users.user1.complexArray[1][1].ultimateTest[1]'); // OUTPUT: 'more success'