简体   繁体   English

仅使用属性访问器(点符号或方括号符号),如何直接设置未定义的嵌套属性?

[英]Using only property accessors (dot notation or bracket notation), how do I set undefined nested properties directly?

In a javascript object, is it possible to set property values of undefined nested keys by only using property accessors (eg dot notation or bracket notation)? 在javascript对象中,是否可以仅通过使用属性访问器 (例如点符号或方括号符号)来设置未定义的嵌套键属性值?

Lodash's _.set function (and TJ Crowder's answer) is similar to what I want, but the structure of the code is different, ie, _.set(state, "some.future.key", "baz") . Lodash的_.set函数(和TJ Crowder的答案)与我想要的类似,但是代码的结构不同,即_.set(state, "some.future.key", "baz")

Are there any libraries that would allow me to directly set the values, ie, state.some.future.key = "baz" ? 是否有任何库可以让我直接设置值,即state.some.future.key = "baz"

Ideally I would want the state to automatically assume the shape of: 理想情况下,我希望状态自动采用以下形式:

state = {
    some: {
        future: {
            key: "baz"
        }
    }
}

You simply create anything that's missing. 您只需创建所有丢失的东西。

 const state = { foo: "bar" }; if (!state.some) { state.some = {}; } if (!state.some.future) { state.some.future = {}; } state.some.future.key = "baz"; console.log(state); 

If it gets to be a lot of inline code, you can provide yourself a function to do it. 如果需要很多内联代码,则可以为自己提供一个函数来执行此操作。 The answers to this question and this question should get you headed the right way if you want to do that. 如果您想这样做, 这个问题这个问题的答案应该可以让您正确地前进。 A simplistic version: 一个简单的版本:

 function setDeep(obj, path, value) { if (typeof path === "string") { path = path.split("."); } const final = path[path.length - 1]; path = path.slice(0, -1); for (const entry of path) { if (!obj[entry]) { obj = obj[entry] = {}; } else { obj = obj[entry]; } } return obj[final] = value; } const state = { foo: "bar" }; setDeep(state, "some.future.key", "baz"); // Or: setDeep(state, ["some", "future", "key"], "baz"); console.log(state); 

...but there are a dozen variations on that. ...但是有很多变化。

The simplest way to solve this problem is the Proxy object as shown below: 解决此问题的最简单方法是Proxy对象,如下所示:

const state = {
    foo: "bar"
}

var stateHandler = {

    get : function(obj,prop){
         if(obj[prop] == undefined){
            obj[prop]= new Proxy({},stateHandler);
         }
         return obj[prop];
    }
  };

var proxyState = new Proxy(state,stateHandler);

proxyState.koo.loo= 9; 
proxyState.too.noo.too.y = 10899;
console.log(proxyState.koo.loo); //9 
console.log(proxyState.too.noo.too.y); // 10899
console.log(proxyState.foo); // bar 

This will allow you to set property at any nested level. 这将允许您在任何嵌套级别设置属性。

To do this state.some.future.key = "baz" use this code 要执行此state.some.future.key = "baz"使用此代码

state.foo='newbar';
state.some={};
state.some.future={};
state.some.future.key='baz';

and when you print state then you will get 当您打印状态时,您将得到

state = {
    foo: "newbar",
    some: {
        future: {
            key: "baz"
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用括号符号在对象文字上创建嵌套属性? - How do I create nested properties on object literals using bracket notation? 在 JavaScript 中,是否有任何方法可以在不使用点符号或括号符号的情况下获取 object 的属性? - In JavaScript, do there exist any ways to get a property of an object without using dot notation or bracket notation? jsdoc:如何使用括号表示法记录属性? - jsdoc: how to document properties using bracket notation? Javascript _ 点符号和括号符号 - Javascript _ Dot notation and Bracket Notation 实现一个函数来访问对象的属性,而不是使用点符号或方括号符号来访问属性? - Implementing a function to access an object's property versus accessing the property using dot notation, or bracket notation? 如何将点表示法的字符串转换为具有值的嵌套 object? - How do I turn a string in dot notation into a nested object with a value? 在括号表示法中嵌套点表示法以创建嵌套对象 - Nesting dot notation within bracket notation to create nested objects 无法使用“ .nested”标志和括号表示法检查嵌套对象的属性 - Unable to check a nested object property by using the “.nested” flag and bracket notation 点和方括号表示法 - Dot and Square Bracket Notation 如何修复括号vs点表示法Angular.js - How can I fix bracket vs dot notation Angularjs
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM