让我们想象这个JS对象如下
document: any = {
id: {
photo: {},
required: true
},
ph: {
photo: {},
required: true
},
zp: {
photo: {},
required: true
}
};
是否可以将所有required
属性设置为false?
答案 0 :(得分:4)
取出键(Object.keys())遍历每个键,然后将所需的属性更改为所需的值
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)
如果您想保持不变,可以使用reduce
代替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)
答案 1 :(得分:0)
我将用JS回答,因为我还没有准备好使用TS:
const myDocument = {
id: {
photo: {},
required: true,
},
ph: {
photo: {},
required: true,
},
zp: {
photo: {},
required: true,
},
};
Object.keys(myDocument).forEach(key => myDocument[key].required = false);
console.log(myDocument);
答案 2 :(得分:0)
您可以使用map更改所有属性值和。该对象参照。您无需创建新变量。
var any = {
id: {
photo: {},
required: true
},
ph: {
photo: {},
required: true
},
zp: {
photo: {},
required: true
}
};
Object.keys(any).map(function(key, index) {
any[key].required =false;
});
console.log(any);
答案 3 :(得分:0)
实际上,您可以简单地使用for ... in遍历对象
let any = {
id: {photo: {}, required: true},
ph: {photo: {}, required: true},
zp: {photo: {}, required: true}
};
for (const key in any)
{
any[key].required = false;
}
console.log(any);