Click here to Skip to main content
15,879,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to read the json document from php and convert it needed in js, but an error occurs. :
cannot read properties of undefined (reading 'length')
What went wrong? How can I loop the result below without using length ?

Here's the code:

What I have tried:

/*php */

$conn = db_connect();
$id = mysqli_fix_string( $conn, $id );

$Json_file = file_get_contents("files/sub/".$id."/".sub.json);
print( $json_file );

/*.js */
$.ajax({ url: "./sub/view_sub.php",
         type:"GET",
         data: { id: id },
         success: function( json ) {
            const result = JSON.parse( json );
            console.log(result.sub)
            console.log(result.sub[1]); // OK result is 'serg' 
            console.log(result.sub[2]); // OK result is 'dgf
            if( result.sub.length > 0 ){   <<== error
                 let i = 0;
                 for( const item of result.sub ){
                     foo_arr[id].input_text(i++, item );
                  }
               }
           }
});
              
// console result
>{1: 'serg', 2: 'dgf', 4: 'dfg ', 6: 'dfge ergre'}  <== console.log(result.sub)
uncaught typeError: Cannot read properties of undefined (reading 'length')
Posted
Updated 5-May-22 22:08pm
v3

Quote:
This is my result /
JavaScript
console.log(result.sub)
{1: 'serg', 2: 'dgf', 4: 'dfg ', 6: 'dfge ergre'} 
Your result is not an array; it's an object which happens to have numeric property names.

If you want to iterate over the properties of the object, you can use the Object.keys method[^]:
JavaScript
const subKeys = Object.keys(result.sub);
for (let i = 0; i < subKeys.length; i++) {
    foo_arr[id].input_text(i, result.sub[subKeys[i]]);
}
 
Share this answer
 
Comments
Chopin2001 6-May-22 4:57am    
thank you. I've been stuck on this issue all day.
Try using:
JavaScript
if( result.length > 0 )


Example:
JavaScript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = fruits.length;

result returns:
4
 
Share this answer
 
Comments
Chopin2001 5-May-22 20:16pm    
This is my result /
console.log(result.sub)
>{1: 'serg', 2: 'dgf', 4: 'dfg ', 6: 'dfge ergre'}
if( result.length > 0 )
uncaught typeError: Cannot read properties of undefined (reading 'length')

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900