如何根据对象在对象中的位置修改对象属性 [英] How to modify an object property given its location within the object

查看:47
本文介绍了如何根据对象在对象中的位置修改对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个对象 obj,我可以使用类似 obj.a.b.c = "new value" 的东西来修改它的属性.但是,我希望能够以编程方式执行此操作,使用数组形式的属性位置.我怎样才能制作一个看起来像这样的函数:

Given an object obj, I can modify its properties by using something like obj.a.b.c = "new value". However, I want to be able to do this programmatically, with the property's location in the form of an array. How can I make a function that looks like this:

modifyProperty(obj, ["a", "b", "c"], "新值");

等价于

obj.a.b.c = "新值";

?

推荐答案

你可以使用 Array#reduce,如果没有可用对象,则使用默认对象.

You could use Array#reduce for it, with a default object if no object is available.

function modifyProperty(object, path, value) {
    var last = path.pop();
    path.reduce(function (r, a) {
        if (!(a in r)) {
            r[a] = {};
        }
        return r[a];
    }, object)[last] = value;
}

var object = {};
modifyProperty(object, ["a", "b", "c"], "new value");
console.log(object);

这篇关于如何根据对象在对象中的位置修改对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆