循环访问对象以获取特定值

时间:2017-11-20 09:39:36

标签: javascript loops object return

我有一个与对象和非对象混合的跟随对象。

{
  "boundingBox": "250,420,124,59",
  "lines": [
    {
      "boundingBox": "281,420,62,15",
      "words": [
        {
          "boundingBox": "281,420,62,15",
          "text": "BLACK"
        }
      ]
    },
    {
      "boundingBox": "250,441,124,16",
      "words": [
        {
          "boundingBox": "250,441,75,16",
          "text": "FOREST"
        },
        {
          "boundingBox": "331,441,43,16",
          "text": "HAM"
        }
      ]
    },
    {
      "boundingBox": "275,463,73,16",
      "words": [
        {
          "boundingBox": "275,464,53,15",
          "text": "290\/570"
        },
        {
          "boundingBox": "332,463,16,15",
          "text": "cal"
        }
      ]
    }
  ]
}

我想要实现的是提取所有文本值。 所以预计从上面返回的是:(黑色,森林,火腿,290/570,cal)。

我之前在一个较小的物体上做过这个:

{
  "boundingBox": "275,463,73,16",
  "words": [
    {
     "boundingBox": "275,464,53,15",
     "text": "290\/570"
     },
     {
      "boundingBox": "332,463,16,15",
      "text": "cal"
     }
    ]
 }

我能够使用以下代码实现(290/570,cal)。

for (x in jsonStruct) {
    $initialValue = "";
    if (typeof(jsonStruct[x]) == "object") {
        //var initialValue = traverseJSON(jsonStruct[x], initialValue);
        var wantedValue = jsonStruct[x];
        for (var i=0;i<wantedValue.length; i++){
            initialValue += wantedValue[i].text +",";
        }
    } else {
        initialValue += x + "->" + jsonStruct[x] + " / ";
    }
}
return initialValue;

但是,在上面列出的更大的对象中,我认为因为某些值不是对象,所以代码在第一个停止执行,而不是对象。我得到的唯一回应是boundingBox-&gt; 250,420,124,59 /。

那么如何让循环遍历整个对象,返回所有文本值,无论它们是否是对象。这么长时间他们会返回所有文本值吗?

非常感谢您的帮助!谢谢!

1 个答案:

答案 0 :(得分:1)

我相信这会成功:

const obj = {
  "boundingBox": "250,420,124,59",
  "lines": [
    {
      "boundingBox": "281,420,62,15",
      "words": [
        {
          "boundingBox": "281,420,62,15",
          "text": "BLACK"
        }
      ]
    },
    {
      "boundingBox": "250,441,124,16",
      "words": [
        {
          "boundingBox": "250,441,75,16",
          "text": "FOREST"
        },
        {
          "boundingBox": "331,441,43,16",
          "text": "HAM"
        }
      ]
    },
    {
      "boundingBox": "275,463,73,16",
      "words": [
        {
          "boundingBox": "275,464,53,15",
          "text": "290\/570"
        },
        {
          "boundingBox": "332,463,16,15",
          "text": "cal"
        }
      ]
    }
  ]
}

const result = obj.lines.reduce(function(acc, line){
    line.words.forEach(function(word){
        acc.push(word.text));
    };
  return acc;
}, []);

//Or in arrow notation:
 const result = obj.lines.reduce((acc, line) => {
    line.words.forEach(word => acc.push(word.text));
  return acc;
}, []);

console.log(result);
// Prints out ["BLACK", "FOREST", "HAM", "290/570", "cal"]

我使用reduce函数,它允许您遍历数组并累积所需的结果。 另请注意箭头符号语法。

希望这有帮助。

相关问题