我想创建一个泛型方法,它将访问嵌套对象属性并更新其作为参数传递的值。
This is my data structure
var student = {
name: 'Tom',
address: {
pincode: 43301,
street: '12th Main',
city: 'Some city',
},
marks: {
sub1: 111,
sub2: 222
}
}
这是我的通用方法的骨架
updatProperty(student, 'marks.sub1', 125) {
// this method should return student object with marks.sub1 to be 125
}
I have refereed this link , but this will only return me a value
答案 0 :(得分:3)
您可以使用reduce方法执行此操作,其中检查当前值是否存在以及字符串键的长度是否等于当前元素,然后更改值。
var student = {"name":"Tom","address":{"pincode":43301,"street":"12th Main","city":"Some city"},"marks":{"sub1":111,"sub2":222}}
function updatProperty(obj, key, value) {
key.split('.').reduce((r, e, i, a) => {
if (r[e] && a.length - 1 == i) r[e] = value
return r[e] || {}
}, obj)
}
updatProperty(student, 'marks.sub1', 125);
console.log(student)

答案 1 :(得分:1)
你走在正确的轨道上。我会继续这样做。这样你可以传递你想要改变的值的数组(即['marks', 'sub1']
),它会改变你想要的任何值。请参阅以下示例,了解我如何更改student.marks.sub1
和student.address.city
:
var student = {
name: 'Tom',
address: {
pincode: 43301,
street: '12th Main',
city: 'Some city',
},
marks: {
sub1: 111,
sub2: 222
}
}
function updateProperty(student, keys, value) {
obj = student;
for(var i=0; i<keys.length-1; i++){
obj = obj[keys[i]];
}
obj[keys[i]] = value;
return student;
}
console.log(updateProperty(student, ['marks', 'sub1'], 125));
console.log(updateProperty(student, ['address', 'city'], 'New York'));
答案 2 :(得分:1)
[立即解决] 我会建议像:
function updatProperty(obj, propPath, value) {
if(!propPath) return false;
const keys = propPath.split('.');
let pointer = obj,
validPath = true;
for (let i = 0; i < keys.length && validPath; i++) {
let key = keys[i];
if(i === (keys.length - 1)) pointer[key] = value;
else {
if(!pointer[key]) validPath = false;
else pointer = pointer[key];
}
}
return validPath;
}
[解释] 跟着你的功能签名,我推理
keys
并导航/验证对象,直到达到想要的道具 - 如果路径对对象有效,一切正常,否则循环停止,函数返回false。我假设但未提及的是函数返回值 - 如果一切顺利则为true,否则为false(无propPath
或对象为&#34;不正确&#34;)。
希望它有所帮助。