Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - iterate through object and change nested properties

This is an object to be processed:

var q = {
    email: {contains: "[email protected]"},
    name: {contains: "someuser"}
};

I would like to go through each key of q and if the corresponding value is an object that has the property contains then replace it with $regex.

like image 511
Ali Celebi Avatar asked May 07 '26 12:05

Ali Celebi


1 Answers

Related information can be found here: JavaScript: Object Rename Key

You can try the following way:

var q = {
    email: {contains: "[email protected]"},
    name: {contains: "someuser"}
};
for(var k in q){
  if(q[k].hasOwnProperty('contains')){
    Object.defineProperty(q[k], '$regex',
                Object.getOwnPropertyDescriptor(q[k], 'contains'));
    delete q[k]['contains'];
  }
}

console.log(q);
like image 181
Mamun Avatar answered May 10 '26 02:05

Mamun



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!