richie
richie

Reputation: 467

Matching Two Separate Javascript Objects based on Properties

Have a pretty complex use case with Objects and am curious what the right way to do this would be.

Please see example code here: http://jsfiddle.net/upp3px3y/1/

Basically, I have a single object (var object) which has multiple objects inside of it. I then have an array of objects (var returnedData) whose entries are objects. I basically want to match the objects inside returnedData, via the name property to the correct object (inside var object), then add it as a separate property to that object...

The ideal state of the data would be something like:

    people: {
        p1: {
            name: "richard",
            nationality: "USA",
            data: {
                 name: "richard",
                 number: "11111",
                 city: "new york"       
            }
        },
        p2: {
            name: "chris",
            nationality: "USA",
            data: {
                 name: "chris",
                 number: "11111",
                 city: "new york"       
            }
        }
    }

I haven't seen much documentation and questions on SO as far as being able to work with so many nested objects. I'm not even sure how to approach this problem, so any suggestions are hugely appreciated.

I feel like the answer may have to do with using Object.keys(obj), but I'm not sure what the best way to traverse into an object within another object would be.

Thanks in advance!

Upvotes: 1

Views: 620

Answers (1)

Will
Will

Reputation: 1299

I would loop through the array, and try to match each index object's name to one of obj's nested objects. Here's an example I wrote for you.

Note: I renamed var object to "obj", since it matches Object too easily.

The top level "For In" is for the upper level "signups, nonsignups" and the nested "For In" is for traversing people. You need to use bracket notation when using variables for object properties.

JSFIDDLE: http://jsfiddle.net/biz79/upp3px3y/5/

JS:

for ( var i = 0; i< returnedData.length; i++) {

    for ( var keys in obj ) {
      if ( obj.hasOwnProperty(keys) ) {    
        for (var propname in obj[keys].people) { 
          if (obj[keys].people.hasOwnProperty(propname)) { 

            if ( obj[keys].people[propname].name === returnedData[i].name ) {

                // when you find a match, add 'data' property and append data object.
                obj[keys].people[propname].data = returnedData[i];
            }

          } 
        } // end for-in
      }
    }  // end for-in
}  // end for

Let me know if this helps.

Upvotes: 1

Related Questions