Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Objects Key Value

I am using jQuery to iterate through a Javascript object and I would like to set the key value of one or more of the objects keys from within the loop.

var children = $(clone).children();
    $.each(obj, function(k, v) {
        if(v == undefined) {
            //Loop through data array and match.
            for(var i=0; i<children.length; i++) {
                var dataId = children[i].id.split('.');
                if(k == dataId[1]) {
                    obj.k = children[i].value; //This is the value I want to set on the key.
                }
            }
        }
    });

The children variable is an array of children (input and select objects) within a div. The loop is passed an object and runs through all the keys in the object. In this case the object is a phone numbers and its keys are similar to number, type, primary etc. but that doesn't matter much. If a key on the object is undefined I want to populate that key with a value from its matching child object.

Everything is working perfectly except I cannot figure out how to set the key with a new value.

like image 717
ryandlf Avatar asked Jan 24 '26 12:01

ryandlf


1 Answers

use

obj[k] = children[i].value;

note that foo['bar'] is equivalent to foo.bar

like image 170
qiao Avatar answered Jan 26 '26 01:01

qiao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!