Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set multiple properties inside JS object

Let's imagine this JS object as below

document: any = {
    id: {
        photo: {},
        required: true
    },
    ph: {
        photo: {},
        required: true
    },
    zp: {
        photo: {},
        required: true
    }
};

is there a way to set all required properties to false?

like image 501
Gandarez Avatar asked Jun 19 '26 05:06

Gandarez


1 Answers

Take the keys out (Object.keys()) loop through each key and change the desired property to desired value

let any = { id: { photo: {}, required: true }, ph: { photo: {},required: true},zp: { photo: {},required: true   }};

Object.keys(any).forEach( e => any[e].required=false)

console.log(any)

If you want immutability you can use reduce instead of forEach

let any = { id: { photo: {}, required: true }, ph: { photo: {},required: true},zp: { photo: {},required: true   }};

let output = Object.keys(any).reduce((op,c) => {
  op[c] = {...any[c],required: false }
  return op
},{})
console.log(output)
like image 116
Code Maniac Avatar answered Jun 21 '26 17:06

Code Maniac



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!