Programing

인덱스로 숫자가 아닌 객체 속성에 액세스 하시겠습니까?

lottogame 2020. 11. 4. 07:39
반응형

인덱스로 숫자가 아닌 객체 속성에 액세스 하시겠습니까?


다음과 같은 배열이있는 경우 :

var arr = ['one','two','three'];

이렇게하면 다른 부분에 액세스 할 수 있습니다.

console.log(arr[1]);

키가 아닌 순서로 객체 속성에 액세스하려면 어떻게해야합니까?

예:

var obj = {
    'something' : 'awesome',
    'evenmore'  : 'crazy'
},
jbo = {
    'evenmore'  : 'crazy',
    'something' : 'awesome'
};

속성 이름을 명시 적으로 사용하지 않고 각 개체의 첫 번째 속성 ( "something"from obj및 "evenmore"from-)을 어떻게 얻 jbo습니까?

자, 여러분 중 일부는 내가 다음과 같은 것을 추구한다고 생각하는 것 같습니다.

console.log(obj['something']);

이것은 사실이 아닙니다. 가능한 경우 첫 번째 예와 마찬가지로 인덱스를 대상으로 특별히 찾고 있습니다.


"가능한 경우 첫 번째 예와 같이 색인을 구체적으로 타겟팅하려고합니다."

아니요, 불가능합니다.

가장 가까운 방법은 객체 키의 배열을 가져 와서 다음을 사용하는 것입니다.

var keys = Object.keys( obj );

...하지만 정의한 순서대로 키가 반환된다는 보장은 없습니다. 따라서 다음과 같이 보일 수 있습니다.

keys[ 0 ];  // 'evenmore'
keys[ 1 ];  // 'something'

이 작업을 수행 할 수있는 유일한 방법은를 사용하여 속성을 제공하는 메서드를 만드는 것입니다 Object.keys();.

var obj = {
    dog: "woof",
    cat: "meow",
    key: function(n) {
        return this[Object.keys(this)[n]];
    }
};
obj.key(1); // "meow"

데모 : http://jsfiddle.net/UmkVn/

이것을 사용하는 모든 객체로 확장 할 수 Object.prototype;있지만 일반적으로 권장되지는 않습니다.

대신 함수 도우미를 사용하세요.

var object = {
  key: function(n) {
    return this[ Object.keys(this)[n] ];
  }
};

function key(obj, idx) {
  return object.key.call(obj, idx);
}

key({ a: 6 }, 0); // 6

Object.values()을 사용하지 않으려면 방법을 사용할 수 있습니다 Object.keys().

Object.keys()주어진 객체의 고유 한 열거 가능한 속성의 배열을 반환하는 메서드와는 반대로 , 예를 들면 다음과 같습니다.

const object1 = {
 a: 'somestring',
 b: 42,
 c: false
};

console.log(Object.keys(object1));

다음 배열을 인쇄합니다.

[ 'a', 'b', 'c' ]

Object.values()메서드는 지정된 객체의 고유 한 열거 가능한 속성 배열을 반환합니다 values.

So if you have the same object but use values instead,

const object1 = {
 a: 'somestring',
 b: 42,
 c: false
};

console.log(Object.values(object1));

You would get the following array:

[ 'somestring', 42, false ]

So if you wanted to access the object1.b, but using an index instead you could use:

Object.values(object1)[1] === 42

You can read more about this method here.


var obj = {
    'key1':'value',
    '2':'value',
    'key 1':'value'
}

console.log(obj.key1)
console.log(obj['key1'])
console.log(obj['2'])
console.log(obj['key 1'])

// will not work
console.log(obj.2)

Edit:

"I'm specifically looking to target the index, just like the first example - if it's possible."

Actually the 'index' is the key. If you want to store the position of a key you need to create a custom object to handle this.


by jquery you can do this:

var arr = $.map(obj,function(value, key) {
    return value;
});
alert(obj[0]);

Get the array of keys, reverse it, then run your loop

  var keys = Object.keys( obj ).reverse();
  for(var i = 0; i < keys.length; i++){
    var key = keys[i];
    var value = obj[key];
    //do stuff backwards
  }

If you are not sure Object.keys() is going to return you the keys in the right order, you can try this logic instead

var keys = []
var obj = {
    'key1' : 'value1',
    'key2' : 'value2',
    'key3' : 'value3',
}
for (var key in obj){
    keys.push(key)
}
console.log(obj[keys[1]])
console.log(obj[keys[2]])
console.log(obj[keys[3]])

you can create an array that filled with your object fields and use an index on the array and access object properties via that

propertiesName:['pr1','pr2','pr3']

this.myObject[this.propertiesName[0]]

참고URL : https://stackoverflow.com/questions/7866275/access-non-numeric-object-properties-by-index

반응형