Justin
Justin

Reputation: 4539

Manipulating JSON object: how to reference and update nested values

I am just getting started with this so I am confused about how I would work with the following.

// so I believe this really isn't an object just a string representation, but for example please excuse the name
var dataObj = "{'id': 1, 
                'data': { 'color': 'red', 
                          'shape' : 'triangle', 
                          'height' : 100, 
                          'width' : 45, 
                           },
                'id': 2, 
                'data': { 'color': 'blue', 
                          'shape' : 'square', 
                          'height' : 75, 
                          'width' : 67, 
                          },
                'id': 3, 
                'data': { 'color': 'orange', 
                          'shape' : 'circle', 
                          'height' : 89, 
                          'width' :24, 
                          }
                }";

so what I am having problems with is how would I update specific subset of the data values by the id (like a SQL UPDATE WHERE kind of thing)? javascript or jquery really doesn't matter to me, just don't know an approach for either.

dataObjUpdate(2);    
function dataObjUpdate (passedID) {

    //access the data by the passedID match and update the color to black
}

appreciate the help guys....

Upvotes: 1

Views: 1453

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276286

If we ignore the comment I left and assume you have a JavaScript object. I see the following problems:

  • Your ids are outside of your nested object.
  • You're using an object but you want a 'list' you can use an array for that.

Here is how I'd structure the object myself:

var data = [{ 
        color : 'red', 
        shape : 'triangle', 
        height : 100, 
        width : 45, 
        id:1
    },
    { 
        color: 'blue', 
        shape : 'square', 
        height : 75, 
        width : 67, 
        id: 2
    },
    {
        color: 'orange', 
        shape : 'circle', 
        height : 89, 
        width :24,
        id :3 
    }];

Now, I can query it like you'd expect using filter:

var id3 = data.filter(function(elem){
             return elem.id === 3;
          })[0];
   id3;//the third object, with id 3

ES6 has a method called find which would save the [0] at the end (which means the first element)

var id3 = data.find(function(elem){
             return elem.id === 3;
          });
   id3;//the third object, with id 3

Or, you can use a simple for loop

var id3 = (function find(arr){
              for(var i=0;i<arr.length;i++){
                  if(arr[i].id === 3){
                      return arr[i];
                  }
              }
          })(data);
id3;

Upvotes: 2

Related Questions