Search code examples
javascriptjqueryarraysjavascript-objects

How to iterate through array of objects and stringify


I've been at this for a bit trying to come up with a solution. I have tested a handful of stack solutions to iterate through nested objects but haven't gotten this to work correctly. My data structure is below.

I've been trying to first off iterate through nested objects which this stack seemed to be similar to mine.

Iterate through Nested JavaScript Objects

However, when I'm in my for loop getting access to geo, value object to grab all of its properties, ip, hostname, city etc I'm coming up empty handed with undefined. Here's a code snippet of what I've tried below.

I'm trying to take all of the keys and values in this entire object and stringify them into a beautiful parameter string to send over to the server in an ajax request.

for (var i = 0; i < myarray.length; i++) {
    var o = myarray[i];
    if (o.name === "geo") {

        o.value.ip;
    }
}
0: {name: "firstname", value: "John"}
1: {name: "lastname", value: "Smith"}
2: {name: "email", value: "[email protected]"}
3: {name: "password", value: "asdsdadasads"}
4: {name: "paypal_email", value: "[email protected]"}
5: {name: "phone", value: "1234567894"}
6: {name: "geo",value: " 
{"ip":"111.111.111.111","hostname":"rr.com","city":"MyCity","region":"Ohio","country":"US","loc":"41.34.23","org":"Inc","postal":"1234","timezone":"America/New_York","readme":"https://www.google.com"}"
__proto__: Object
length: 7
__proto__: Array(0)

Solution

  • The problem is that the structure of the geo object is odd:

    name: "geo",value: "{"ip":"111.111.111.111","hostname":"rr.com","city":"MyCity","region":"Ohio","country":"US","loc":"41.34.23","org":"Inc","postal":"1234","timezone":"America/New_York","readme":"https://www.google.com"}"
    

    The value looks to be a string in JSON notation. You'll have to parse it first in order to look up properties on it:

    if (o.name === "geo") {
        const nestedObj = JSON.parse(o.value);
        console.log(nestedObj.ip);
    }
    

    You might also consider fixing whatever's serving you that object so that the value is an actual object - if that's possible (it may not be, but it would make the code make a lot more sense).

    You can also consider using .find instead of a for loop, to make the code shorter and more elegant:

    const json = myarray.find(({ name }) => name === 'geo').value;
    const nestedObj = JSON.parse(json);
    

    (if the geo object may not exist, test for undefined first, of course)