Home > Enterprise >  Extract data from Object Array
Extract data from Object Array

Time:01-28

this is about image to text (OCR) converter using terrasect. Refering to a working codepen demo at enter image description here

function result(data){
  var r = $(".result");
 console.log(data);
  r.append(
    "<div class='sixteen wide column output'>success"  
    "<div class='ui message'><pre>"   data.text  "</pre></div>"   
    "</div>"
  );
}

enter image description here

CodePudding user response:

You could use DOMParser to parse the HTML and then get the page_1 element and then get its title. After that, you could parse the title to get the numbers by selecting the numbers between bbox and ;, then you could take the third and fourth number.

Modify the function result(data) to this:

function result(data){
  var r = $(".result");
 
  const parser = new DOMParser();
  const parsed = parser.parseFromString(data.html, 'text/html');
  const firstOccurrence = parsed.getElementById('page_1').getAttribute('title');
  const numbers = firstOccurrence.split('bbox ')[1].split(';')[0].split(' ');

  console.log("green numbers:", numbers[2], numbers[3])
  
  r.append(
    "<div class='sixteen wide column output'>success"  
    "<div class='ui message'><pre>"   data.text  "</pre></div>"   
    "</div>"
  );
}

Here is the working fork codepen.

CodePudding user response:

Loop through the object array, extract the data from each object, create elements (a div and three paragraphs), add the data to the elements, and then append the elements to the div and the div to the body. This will result in three divs with the data from each object being displayed on the page.

// Object Array
var data = [
    {name: "John Smith", age: 25, city: "New York"},
    {name: "Jane Doe", age: 30, city: "Los Angeles"},
    {name: "Bob Smith", age: 35, city: "Chicago"}
];

// Loop through the object array
for (var i = 0; i < data.length; i  ) {
    // Extract data
    var name = data[i].name;
    var age = data[i].age;
    var city = data[i].city;
    
    // Create elements
    var div = document.createElement("div");
    var p1 = document.createElement("p");
    var p2 = document.createElement("p");
    var p3 = document.createElement("p");
    
    // Add data to elements
    p1.innerHTML = "Name: "   name;
    p2.innerHTML = "Age: "   age;
    p3.innerHTML = "City: "   city;
    
    // Append elements to div
    div.appendChild(p1);
    div.appendChild(p2);
    div.appendChild(p3);
    
    // Append div to the body
    document.body.appendChild(div);
}

Using jQuery

// Loop through the data array
$.each(data, function(index, item) {
    // Extract the name and age properties
    var name = item.name;
    var age = item.age;
    
    // Create a new div element to append the data
    var newDiv = $("<div>").append(name   " - "   age);
    
    // Append the new div to the body of the page
    $("body").append(newDiv);
});

  • Related