给出一个像:
这样的对象var house = {
bedrooms: 4,
baths: 2,
city: "Austin",
details: {
price: 500000,
closing: {
date: "May 7"
}
}
}
我正在尝试创建一个允许我设置现有属性值的方法,或者,如果该属性不存在,则创建一个具有该值的新属性。
因此输入可能是:
house.setProp("details.closing.date", "June 1");
house.setProp("details.newProp", "newProp Value");
输出将是:
var house = {
bedrooms: 4,
baths: 2,
city: "Austin",
details: {
newProp: "newProp Value",
price: 500000,
closing: {
date: "June 1"
}
}
}
这是我到目前为止的尝试,虽然它适用于第一个深度,但我无法弄清楚如何访问/创建多个深度。你能帮帮忙吗?谢谢!
Object.prototype.setProp = function(path, newValue)
{
var keys = path.split('.');
obj = this;
if (keys.length > 1)
{
setProp(obj[keys.shift()], newValue);
}
else
{
obj[keys[0]] = newValue;
}
}
答案 0 :(得分:1)
var house = {
bedrooms: 4,
baths: 2,
city: "Austin",
details: {
price: 500000,
closing: {
date: "May 7"
}
}
}
house.details.closing.date= "June 1";
house.details.newProp="newProp Value";
答案 1 :(得分:0)
如果您需要访问静态属性,则无需执行任何特殊操作
house.details.closing.data = "June 1";
但是,如果您有动态的属性列表,则可以使用dotty轻松完成此操作
var dotty = require("dotty");
dotty.put(house, "details.closing.date", "June 1");
相当于
var dotty = require("dotty");
dotty.put(house, ["details", "closing", "date"], "June 1");
答案 2 :(得分:0)
您可以使用reduce
:
var setProp = function(path, value, obj) {
path = path.split('.')
path.reduce(function(acc, k, i) {
if (i === path.length-1) {
acc[k] = value
} else if (typeof acc[k] !== 'object') {
acc[k] = {}
}
return acc[k]
}, obj)
return obj
}
var o = {a: {}}
setProp('a.b.c', 1, o)
console.log(o) // {a:{b:{c:1}}