解析嵌套对象不会使用javascript遍历整个列表

解析嵌套对象不会使用javascript遍历整个列表,javascript,nested-loops,Javascript,Nested Loops,我正在尝试分析以下格式的嵌套对象: const obj = { "and": [ { "!=": [ { "var": "name" }, "name1" ] }, { "in": [ {

我正在尝试分析以下格式的嵌套对象:

const obj = {
  "and": [
      {
        "!=": [
          {
            "var": "name"
          },
          "name1"
        ]
      },
      {
        "in": [
          {
            "var": "hobbies"
          },
          "jogging, video games"
        ]
      }
    ]
};
我创建了一个函数来解析它:

const isOperatorCode(code) => {
  const allowedOperatorCodes = ['in', '<=', '!=', '=='];
  return allowedOperatorCodes.includes(code);
}

const parseObject = (arg, result={}) => {
  if (arg === undefined || arg === null) return arg;

  if (arg.constructor === Object && Object.keys(arg).length) {
    for (const key in arg) {
      const value = arg[key];
      if (key === 'and' || key === 'or' || key === '!') {
        result.operator = key === '!' ? 'not' : key;
        result.operands = [];
        return parseObject(value, result);
      }
      if (isOperatorCode(key)) {
        const newItem = {
          operator: key,
          attribute: value[0].var,
          value: value[1]
        }

        result.operands.push(newItem);

      }
    }
  }

  if(Array.isArray(arg) && arg.length) {
    for (const k of arg) {
      return parseObject(k, result);
    }
  }
  return result;
  
}
我知道数组不会保留元素的跟踪,以继续在不同的项之间循环。有什么想法或建议来跟踪数组元素并循环它们吗?

返回parseObject(k,result)停止循环的执行,因此您只需要获取第一项

for(参数的常数k){
return parseObject(k,result);//return中断循环。仅处理第一项。
}
也许这会更有意义

返回args.map(k=>parseObject(k,result));//处理所有条目,返回一个数组。

如果只在最后返回
,您将获得预期结果

const obj={
“和”:[{
"!=": [{
“变量”:“名称”
},“名称1”]
}, {
“在”:[{
“var”:“爱好”
},“慢跑、电子游戏”]
}]
};
常量等运算符代码=(代码)=>{

const allowedOperatorCodes=['in','您可以采用递归方法,将look-at对象与
var
作为键

const
convert=object=>{
如果(!object | | typeof object!=='object')返回object;
常量[运算符,值]=对象。条目(对象)[0];
返回值[0]&&typeof值[0]==“对象”&&var”在值[0]中
?{运算符,属性:值[0]。变量,值:值[1]}
:{运算符,操作数:values.map(convert)};
},
对象={和:[{var:“name”},“name1”]},{in:[{var:“嗜好”},“慢跑,视频游戏”]},
结果=转换(对象);
console.log(结果);

.as console wrapper{max height:100%!important;top:0;}
什么是
isOperatorCode
?这是一个简单的函数,用于检查允许的运算符代码列表中是否存在运算符。允许的代码是什么?我更新了问题,并添加了一个简单的函数来澄清问题
{"operator":"and","operands":[{"operator":"!=","attribute":"name","value":"name1"}]}

it should be:

{"operator":"and","operands":[{"operator":"!=","attribute":"name","value":"name1"}, {"operator":"in","attribute":"hobbies","value":"sport, video games"}]}