cuốn sách gpt4 ai đã làm

Javascript 添加一个带有字符串值名称的属性

In lại Tác giả: Walker 123 更新时间:2023-11-28 12:15:30 27 4
mua khóa gpt4 Nike

是否可以使用字符串中的值向 javascript/json 对象添加属性?

let myObj= {};

for{prop in propsToAdd){
myObj.addProp(prop.name, prop.type);
}

myObj.addProp = function (name, type) {
// here i need to add another json object
// with the name as the name of the property
// and a property called type with the value of the param type
}

Ví dụ:

myObj = {}
myObj.addProb("title","string");
myObj.addProp("id","integer")

结果应该与:

myObj = {
"title": {
"type": "string"
},
"id": {
"type": "integer"
},
}

我正在考虑使用 JSON.stringify (一起构建字符串)和 JSON.parse .

但是如果有更优雅的方式就好了。

câu trả lời hay nhất

你可以做这样的事情。请注意,您可能希望两者都使用 addProp, thay vì addProb:

const myObj = {};
// keep the function from being printed when printing the object
Object.defineProperty(myObj, 'addProp', {
value: function addProp(key, type) {
myObj[key] = { type };
},
enumerable: false
});

myObj.addProp("title","string");
myObj.addProp("id","integer");
console.log(myObj);

关于Javascript 添加一个带有字符串值名称的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50563614/

27 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress