遍历对象以获取特定值

3
我有一个包含对象和非对象的混合对象。
{
  "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"
        }
      ]
    }
  ]
}

我希望实现的是提取所有文本值的功能。因此,从上面期望返回的内容是:(black, forest, ham, 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->250,420,124,59 /。

那么我该如何编写一个循环,循环遍历整个对象,并返回所有文本值,无论它们是否是对象,只要它们返回所有文本值即可?

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


输入的结构不固定吗?因为在较大的对象中有 lines 而在较小的对象中没有。 - Naman Kheterpal
1个回答

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函数,可以对数组进行迭代并累加您想要的结果。 还请注意箭头符号表示法。

希望这有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接