키 / 값 자바 스크립트 객체의 키를 얻는 가장 좋은 방법
다음과 같은 JS 객체가있는 경우 :
var foo = { 'bar' : 'baz' }
나는 그것이 알고 있다면 foo
그 기본 키 / 값 구조를 가지고 있지만 키의 이름을 모르는 그것을 얻을 수있는 가장 쉬운 방법은 무엇입니까? for ... in
? $.each()
? 더 좋은 것이 있기를 바랍니다 ....
모든 키를 얻으려면 ECMAScript 5가 도입되었습니다Object.keys
. 이것은 최신 브라우저에서만 지원되지만 MDC 설명서 는 대체 구현 ( for...in
btw 도 사용 )을 제공합니다.
if(!Object.keys) Object.keys = function(o){
if (o !== Object(o))
throw new TypeError('Object.keys called on non-object');
var ret=[],p;
for(p in o) if(Object.prototype.hasOwnProperty.call(o,p)) ret.push(p);
return ret;
}
물론 키와 가치를 모두 원한다면 for...in
유일한 솔루션입니다.
for 루프를 사용하여 객체 내부를 반복합니다.
for(var i in foo){
alert(i); // alerts key
alert(foo[i]); //alerts key's value
}
또는
Object.keys(foo)
.forEach(function eachKey(key) {
alert(key); // alerts key
alert(foo[key]); // alerts value
});
다음과 같이 반복하지 않고 각 키에 개별적으로 액세스 할 수 있습니다.
var obj = { first: 'someVal', second: 'otherVal' };
alert(Object.keys(obj)[0]); // returns first
alert(Object.keys(obj)[1]); // returns second
주어진 객체 :
var foo = { 'bar' : 'baz' }
를 얻으려면 다음 bar
을 사용하십시오.
Object.keys(foo)[0]
를 얻으려면 다음 baz
을 사용하십시오.
foo[Object.keys(foo)[0]]
단일 객체 가정
가장 간단하고 쉬운 방법입니다. 이것이 우리가 이것을하는 방법입니다.
var obj = { 'bar' : 'baz' }
var key = Object.keys(obj)[0];
var value = obj[key];
console.log("key = ", key) // bar
console.log("value = ", value) // baz
하나 라이너 당신을 위해 :
const OBJECT = {
'key1': 'value1',
'key2': 'value2',
'key3': 'value3',
'key4': 'value4'
};
const value = 'value2';
const key = Object.keys(OBJECT)[Object.values(OBJECT).indexOf(value)];
window.console.log(key); // = key2
나는 같은 문제가 있었고 이것이 효과가 있었다.
//example of an Object
var person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
};
//How to access a single key or value
var key = Object.keys(person)[0];
var value = person.firstName;
// iterate through key-value gracefully
const obj = { a: 5, b: 7, c: 9 };
for (const [key, value] of Object.entries(obj)) {
console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
}
MDN 참조
이외의 것은 보이지 않습니다 for (var key in foo)
.
이외의 다른 방법은 없습니다 for ... in
. 그것을 사용하고 싶지 않다면 (아마도 hasOwnProperty
각 반복 에서 테스트 해야하는 것이 비효율적 입니까?) 다른 구성을 사용하십시오 (예 : kvp 배열).
[{ key: 'key', value: 'value'}, ...]
을 언급 $.each()
했으므로 jQuery 1.6 이상에서 작동하는 편리한 방법이 있습니다.
var foo = { key1: 'bar', key2: 'baz' };
// keys will be: ['key1', 'key2']
var keys = $.map(foo, function(item, key) {
return key;
});
가장 쉬운 방법은 Underscore.js를 사용하는 것입니다.
열쇠
_.keys (object) 객체 속성의 모든 이름을 검색합니다.
_.keys ({1 : 1, 2 : 2, 3 : 3}); => [ "1", "2", "3"]
예, 추가 라이브러리가 필요하지만 너무 쉽습니다!
Object.keys() The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
var arr1 = Object.keys(obj);
Object.values() The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
var arr2 = Object.values(obj);
For more please go here
use for each loop for accessing keys in Object or Maps in javascript
for(key in foo){
console.log(key);//for key name in your case it will be bar
console.log(foo[key]);// for key value in your case it will be baz
}
Note: you can also use
Object.keys(foo);
it will give you like this output:
[bar];
Well $.each
is a library construct, whereas for ... in
is native js, which should be better
for showing as a string, simply use:
console.log("they are: " + JSON.stringify(foo));
참고URL : https://stackoverflow.com/questions/6268679/best-way-to-get-the-key-of-a-key-value-javascript-object
'IT' 카테고리의 다른 글
z-index가 작동하지 않는 이유는 무엇입니까? (0) | 2020.06.03 |
---|---|
파이썬은 첫 글자 만 대문자 (0) | 2020.06.03 |
역사없이 git repo를 복사하십시오. (0) | 2020.06.03 |
“java.net.BindException : 이미 사용중인 주소 : JVM_Bind”오류를 어떻게 해결합니까? (0) | 2020.06.03 |
Java에서 선행 0을 유지하면서 바이트 배열을 16 진수 문자열로 변환하는 방법은 무엇입니까? (0) | 2020.06.03 |