我是javascript的初学者,我在动态创建此对象时遇到问题。必须从文本条目中提取所有名称并动态插入到对象中。
var object = {
"users" : {
// Names dynamically inserted
"Isaac" : {
"name" : "Isaac de Araujo Meneses",
"age" : "25"
}
"John"{
"name" : "John Miller",
"age" : "32"
}
}
}
这是我写的代码:
var name = form.name.value;
var object = {
"users" : {
// Names dynamically inserted
name : {
"name" : name,
"age" : "25"
}
}
}
答案 0 :(得分:2)
基本代码:
var object = {
users: {
"John": {
name: "John Smith",
age: "140" // Why not?
}
}
}
添加新用户:
var name = form.name.value;
var age = form.age.value;
object.users[name] = {
name: name,
age: age
}
答案 1 :(得分:1)
您可以动态设置对象键:
const obj = {
a: 1,
b: 2,
c: 3,
d: 4,
e: 5
};
const desiredKeys = ['a', 'c', 'd'];
const result = desiredKeys.reduce((acc, key) => {
acc[key] = obj[key];
return acc;
}, {});
console.log(result);