慕姐8265434
编辑:错过了问题中的“嵌套数组”部分。试试这个:function setProperty(object, key, value) { if(Array.isArray(object)){ let newArray = []; object.forEach((obj, index) => { newArray.push(setProperty(obj, key, value)); }); return newArray; } else if(typeof object === 'object' && object != null) { object[key] = value; Object.entries(object).forEach(item => { if(Array.isArray(item[1])) { let listKey = item[0]; let newList = setProperty(item[1], key, value); object[listKey] = newList; } }); return object; }}用法setProperty(object, "isDisabled", true);setProperty(object, "isDisabled", false);setProperty(object, "someKey", "Some Value");运行以下代码片段进行演示function setProperty(object, key, value) { if (Array.isArray(object)) { let newArray = []; object.forEach((obj, index) => { newArray.push(setProperty(obj, key, value)); }); return newArray; } else if (typeof object === 'object' && object != null) { object[key] = value; Object.entries(object).forEach(item => { if (Array.isArray(item[1])) { let listKey = item[0]; let newList = setProperty(item[1], key, value); object[listKey] = newList; } }); return object; }}function changeProp() { let object = { metaForm: [{ id: 1, text: 'abc', AdditionalVal: [] }, { id: 1, text: 'abc', AdditionalVal: [{ id: 1, text: 'add', compositeConfig: [] }, ] }, { id: 1, text: 'abc', AdditionalVal: [{ id: 1, text: '123', compositeConfig: [{ id: 1, text: 'composit', compositeConfig: [] }] }, ] } ], tabData: [{ composite: false, compositeFieldList: [], id: 3576, tenantId: "1", }, { composite: false, compositeFieldList: [{ id: 1, text: 'composit2', compositeConfig: [] }, { id: 1, text: 'composit3', compositeConfig: [] }, ], id: 3576, tenantId: "1", }, ] }; document.getElementById("old").innerHTML = JSON.stringify(object, null, 4); let name = document.getElementById("propertyName").value; if (name == null || name == "") name = "isDisabled" setProperty(object, name, true); document.getElementById("result").innerHTML = JSON.stringify(object, null, 4);}<div> <h3> Enter the name of the property and click on the <strong>Set Property</strong> button.<br/> Default name is <i>isDisabled</i></h3> <input type="text" id="propertyName" name="propertyName" placeholder="Property name" /> <button onclick="changeProp();">Set Property</button> <h2>Object</h2> <pre id="old"></pre> <br/> <h2>Updated</h2> <pre id="result"></pre></div>