변수를 사용하여 객체 속성에 동적으로 액세스
동적 이름을 사용하여 개체의 속성에 액세스하려고합니다. 이것이 가능한가?
const something = { bar: "Foobar!" };
const foo = 'bar';
something.foo; // The idea is to access something.bar, getting "Foobar!"
객체의 속성 에 액세스하는 방법 에는 두 가지가 있습니다 .
- 점 표기법 :
something.bar
- 대괄호 표기 :
something['bar']
대괄호 사이의 값은 모든 표현식이 될 수 있습니다. 따라서 속성 이름이 변수에 저장되면 대괄호 표기법을 사용해야합니다.
var foo = 'bar';
something[foo];
// both x = something[foo] and something[foo] = x work as expected
이것이 내 해결책입니다.
function resolve(path, obj) {
return path.split('.').reduce(function(prev, curr) {
return prev ? prev[curr] : null
}, obj || self)
}
사용 예 :
resolve("document.body.style.width")
// or
resolve("style.width", document.body)
// or even use array indexes
// (someObject has been defined in the question)
resolve("part.0.size", someObject)
// returns null when intermediate properties are not defined:
resolve('properties.that.do.not.exist', {hello:'world'})
자바 스크립트에서는 다음과 같이 액세스 할 수 있습니다.
- 점 표기법-
foo.bar
- 대괄호-
foo[someVar]
또는foo["string"]
그러나 두 번째 경우에만 속성에 동적으로 액세스 할 수 있습니다.
var foo = { pName1 : 1, pName2 : [1, {foo : bar }, 3] , ...}
var name = "pName"
var num = 1;
foo[name + num]; // 1
// --
var a = 2;
var b = 1;
var c = "foo";
foo[name + a][b][c]; // bar
다음은 두 문자열을 연결하여 동적으로 생성 된 속성 이름을 사용하여 개체의 속성에 액세스하는 방법에 대한 ES6 예제입니다.
var suffix = " name";
var person = {
["first" + suffix]: "Nicholas",
["last" + suffix]: "Zakas"
};
console.log(person["first name"]); // "Nicholas"
console.log(person["last name"]); // "Zakas"
이를 계산 된 속성 이름 이라고 합니다.
You can achieve this in quite a few different ways.
let foo = {
bar: 'Hello World'
};
foo.bar;
foo['bar'];
The bracket notation is specially powerful as it let's you access a property based on a variable:
let foo = {
bar: 'Hello World'
};
let prop = 'bar';
foo[prop];
This can be extended to looping over every property of an object. This can be seem redundant due to newer JavaScript constructs such as for ... of ..., but helps illustrate a use case:
let foo = {
bar: 'Hello World',
baz: 'How are you doing?',
last: 'Quite alright'
};
for (let prop in foo.getOwnPropertyNames()) {
console.log(foo[prop]);
}
Both dot and bracket notation also work as expected for nested objects:
let foo = {
bar: {
baz: 'Hello World'
}
};
foo.bar.baz;
foo['bar']['baz'];
foo.bar['baz'];
foo['bar'].baz;
Object destructuring
We could also consider object destructuring as a means to access a property in an object, but as follows:
let foo = {
bar: 'Hello World',
baz: 'How are you doing?',
last: 'Quite alright'
};
let prop = 'last';
let { bar, baz, [prop]: customName } = foo;
// bar = 'Hello World'
// baz = 'How are you doing?'
// customName = 'Quite alright'
You can do it like this using Lodash get
_.get(object, 'a[0].b.c');
UPDATED
I have take comments below into consideration and agreed. Eval is to be avoided.
Accessing root properties in object is easily achieved with obj[variable]
, but getting nested complicates thing. Not to write already written code I suggest to use lodash.get
.
Example
// Accessing root property
var rootProp = 'rootPropert';
_.get(object, rootProp, defaultValue);
// Accessing nested property
var listOfNestedProperties = [var1, var2];
_.get(object, listOfNestedProperties);
Lodash get can be used on different ways, here is link to the documentation lodash.get
Whenever you need to access property dynamically you have to use square bracket for accessing property not "." operator
Syntax: object[propery}
const something = { bar: "Foobar!" };
const foo = 'bar';
// something.foo; -- not correct way at it is expecting foo as proprty in something={ foo: "value"};
// correct way is something[foo]
alert( something[foo])
It gets interesting when you have to pass parameters to this function as well.
Code jsfiddle
var obj = {method:function(p1,p2,p3){console.log("method:",arguments)}}
var str = "method('p1', 'p2', 'p3');"
var match = str.match(/^\s*(\S+)\((.*)\);\s*$/);
var func = match[1]
var parameters = match[2].split(',');
for(var i = 0; i < parameters.length; ++i) {
// clean up param begninning
parameters[i] = parameters[i].replace(/^\s*['"]?/,'');
// clean up param end
parameters[i] = parameters[i].replace(/['"]?\s*$/,'');
}
obj[func](parameters); // sends parameters as array
obj[func].apply(this, parameters); // sends parameters as individual values
For example :
a = [ {b:[{a:1,b:[{c:1,d:2}]}]} ]
Instead of :
if(a && a[0] && a[0].b && a[0].b[0] && a[0].b[0].b && a[0].b[0].b[0] && a[0].b[0].b[0].d && a[0].b[0].b[0].d == 2 ) // true
We can now :
if( getValue('a[0].b[0].b[0].d') == 2 ) // true
Here is the code
/**
* @method getValue
* @description simplifies checking for existance and getting a deeply nested value within a ceratin context
* @argument {string} s string representation of the full path to the requested property
* @argument {object} context optional - the context to check defaults to window
* @returns the value if valid and set, returns undefined if invalid / not available etc.
*/
var getValue = function( s, context ){
var fn = function(){
try{
return eval(s);
}catch(e){
return undefined;
}
}
return fn.call(context||window,s);
}
There is a few possibilities:
const test = {
prop1: {
prop2: {
prop3: "I'm very nested"
}
}
const test1 = test.prop1.prop2.prop3
const test2 = test['prop1']['prop2']['prop3']
const test3 = test['prop1.prop2.prop3'] //will return undefined
const test4 = _.get(test, 'prop1.prop2.prop3') //use lodash
If you want to get nested value dynamically (e.g. by variable), your best option will be to use lodash
.
You should use JSON.parse
, take a look at https://www.w3schools.com/js/js_json_parse.asp
const obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}')
console.log(obj.name)
console.log(obj.age)
const something = { bar: "Foobar!" };
const foo = 'bar';
something[\`${foo}\`];
참고URL : https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable
'code' 카테고리의 다른 글
제네릭 클래스 또는 메서드의 멤버에서 T 유형을 가져 오는 방법은 무엇입니까? (0) | 2020.10.02 |
---|---|
이미지를 깔끔하게 빌드하기 위해 Docker를 강제하는 방법 (0) | 2020.10.02 |
JavaScript에서 클래스를 정의하는 데 사용할 수있는 기술은 무엇이며 그 장단점은 무엇입니까? (0) | 2020.09.30 |
C #에서 string.Empty 또는 String.Empty 또는 ""를 사용하여 문자열을 초기화해야합니까? (0) | 2020.09.30 |
Android 텍스트 뷰 주위에 테두리를 어떻게 두나요? (0) | 2020.09.30 |