Object.keys返回json对象的索引值

时间:2018-10-09 05:16:10

标签: javascript json

我有一个json对象,如下所示:

{
  "firstObject": [
    {
      "element": ".branding",
      "details": "Hello"
    },
    {
      "element": "button.login",
      "details": "Hi "
    },
    {
      "element": "#step3",
      "details": "How are you "
    }
  ],
  "secondObject": [
    {
      "element": ".branding",
      "details": "Hello"
    },
    {
      "element": ".step12",
      "details": "Hi "
    },
    {
      "element": "#step2",
      "details": "How are you "
    }
  ]
}

我有下面的函数,上面的对象作为参数(步骤)传递:

function getStateSteps (state, steps) {
    console.log('TESTTT  1', steps);
    let x = Object.keys(steps);
    console.log('TESTTT  2', x);
}

在这里,在TESTTT 2日志中,“ x”返回的是字符串的索引值而不是JSON对象的键。但是当我在浏览器控制台中检查同一对象时,我得到的是正确的输出。 我已经附上了浏览器控制台的屏幕截图。有人可以指出出什么问题了吗?

控制台屏幕截图

enter image description here

2 个答案:

答案 0 :(得分:0)

再次检查。我刚刚在控制台中尝试过,它的打印效果完全符合预期。

enter image description here

在使用json对象之前尝试JSON.parse(steps),看看是否有帮助。

function getStateSteps (state, steps) {
    steps = JSON.parse(steps)
    console.log('TESTTT  1', steps);
    let x = Object.keys(steps);
    console.log('TESTTT  2', x);
}

答案 1 :(得分:0)

这很好用:

const data = {
  "firstObject": [
    {
      "element": ".branding",
      "details": "Hello"
    },
    {
      "element": "button.login",
      "details": "Hi "
    },
    {
      "element": "#step3",
      "details": "How are you "
    }
  ],
  "secondObject": [
    {
      "element": ".branding",
      "details": "Hello"
    },
    {
      "element": ".step12",
      "details": "Hi "
    },
    {
      "element": "#step2",
      "details": "How are you "
    }
  ]
};

function getStateSteps (state, steps) {
    console.log('TESTTT  1', steps);
    let x = Object.keys(steps);
    console.log('TESTTT  2', x);
}

getStateSteps(null, data);

您是否将其从更广泛的实现中剥离出来,也许错过了关键功能?

您的开发环境是什么?