etc./StackOverFlow

JavaScript 개체를 표시하려면 어떻게 해야 합니까?

청렴결백한 만능 재주꾼 2021. 12. 30. 01:24
반응형

질문자 :maxjackie


변수를 alert 할 때와 같이 JavaScript 개체의 내용을 문자열 형식으로 표시하려면 어떻게 해야 합니까?

동일한 형식으로 개체를 표시하고 싶습니다.



JSON.stringify 메서드를 사용합니다. 중첩된 개체와 함께 작동하며 모든 주요 브라우저에서 이 방법을 지원합니다.

 str = JSON.stringify(obj); str = JSON.stringify(obj, null, 4); // (Optional) beautiful indented output. console.log(str); // Logs output to dev tools console. alert(str); // Displays output using window.alert()

Mozilla API 참조 및 기타 예제에 대한 링크입니다.

 obj = JSON.parse(str); // Reverses above operation (Just in case if needed.)

이 Javascript 오류가 발생하면 사용자 정의 JSON.stringify 교체기를 사용하십시오.

 "Uncaught TypeError: Converting circular structure to JSON"

Sandeep

디버깅 목적으로 개체를 인쇄하려면 다음 코드를 사용하세요.

 var obj = { prop1: 'prop1Value', prop2: 'prop2Value', child: { childProp1: 'childProp1Value', }, } console.log(obj)

표시됩니다:

스크린샷 콘솔 크롬

참고: 개체만 기록해야 합니다. 예를 들어 다음은 작동하지 않습니다.

 console.log('My object : ' + obj)

참고 ' log 메서드에서 쉼표를 사용할 수도 있습니다. 그러면 출력의 첫 번째 줄은 문자열이 되고 그 다음에는 객체가 렌더링됩니다.

 console.log('My object: ', obj);

Triptych

var output = ''; for (var property in object) { output += property + ': ' + object[property]+'; '; } alert(output);

Flavius Stef

console.dir(object) :

지정된 JavaScript 개체의 속성에 대한 대화형 목록을 표시합니다. 이 목록에서는 펼침 삼각형을 사용하여 자식 개체의 내용을 검사할 수 있습니다.

console.dir() 기능은 비표준입니다. MDN 웹 문서 보기


Pizzaiola Gorgonzola

이 시도 :

 console.log(JSON.stringify(obj))

이것은 객체의 stringify 버전을 인쇄할 것입니다. 따라서 [object] 대신 object의 내용을 얻습니다.


Abhishek Goel

음, Firefox(자세한 정보는 @Bojangles 덕분에)에는 객체를 JSON 및 function(){} Object.toSource() 메서드가 있습니다.

대부분의 디버깅 목적으로 충분합니다.


alamar

경고를 사용하여 개체를 인쇄하려면 다음과 같이 하십시오.

alert("myObject is " + myObject.toSource());

각 속성과 해당 값을 문자열 형식으로 인쇄해야 합니다.


Garry

데이터를 표 형식으로 보려면 다음을 사용할 수 있습니다.

 console.table(obj);

테이블 열을 클릭하면 테이블을 정렬할 수 있습니다.

표시할 열을 선택할 수도 있습니다.

 console.table(obj, ['firstName', 'lastName']);

여기에서 console.table에 대한 자세한 정보를 찾을 수 있습니다.


Vlad Bezden

기능:

 var print = function(o){ var str=''; for(var p in o){ if(typeof o[p] == 'string'){ str+= p + ': ' + o[p]+'; </br>'; }else{ str+= p + ': { </br>' + print(o[p]) + '}'; } } return str; }

용법:

 var myObject = { name: 'Wilson Page', contact: { email: 'wilson@hotmail.com', tel: '123456789' } } $('body').append( print(myObject) );

예시:

http://jsfiddle.net/WilsonPage/6eqMn/


wilsonpage

util.inspect(obj) 사용하여 객체를 인쇄할 수 있습니다. 깊이를 명시해야 합니다. 그렇지 않으면 대상의 얕은 인쇄만 남게 됩니다.


astone26

단순히 사용

 JSON.stringify(obj)

예시

 var args_string = JSON.stringify(obj); console.log(args_string);

또는

 alert(args_string);

또한 자바스크립트 함수에서 노트는 객체로 간주됩니다.

추가 참고 사항:

실제로 이와 같은 새 속성을 할당하고 console.log에 액세스하거나 경고에 표시할 수 있습니다.

 foo.moo = "stackoverflow"; console.log(foo.moo); alert(foo.moo);

Raza Rafaideen

주의: 이 예에서 yourObj는 검사하려는 개체를 정의합니다.

먼저 객체를 표시하는 데 가장 덜 좋아하지만 가장 많이 활용되는 방법은 다음과 같습니다.

이것은 객체의 내용을 표시하는 사실상의 방법입니다.

 console.log(yourObj)

다음과 같은 것을 생성합니다. 여기에 이미지 설명 입력

가장 좋은 해결책은 개체 키를 살펴본 다음 개체 값을 확인하는 것입니다. 실제로 개체가 무엇을 보유하고 있는지 확인하려면...

 console.log(Object.keys(yourObj)); console.log(Object.values(yourObj));

다음과 같이 출력됩니다. 여기에 이미지 설명 입력 (위 사진: 객체에 저장된 키/값)

ECMAScript 2016 이상을 사용하는 경우에도 이 새로운 옵션이 있습니다.

 Object.keys(yourObj).forEach(e => console.log(`key=${e} value=${yourObj[e]}`));

이렇게하면 깔끔한 출력이 생성됩니다. 여기에 이미지 설명 입력 이전 답변에서 언급한 솔루션: console.log(yourObj) 는 너무 많은 매개변수 를 표시하며 원하는 데이터를 표시하는 가장 사용자 친화적인 방법이 아닙니다 . 그렇기 때문에 키와 값을 별도로 로깅하는 것이 좋습니다.

다음 :

 console.table(yourObj)

이전 댓글의 누군가가 이것을 제안했지만 저에게는 효과가 없었습니다. 다른 브라우저에서 다른 사람에게 효과가 있다면 영광입니다! 참고로 여기에 코드를 넣어두겠습니다! 콘솔에 다음과 같이 출력합니다. 여기에 이미지 설명 입력


Max Alexander Hanna

이것을 사용하십시오:

 console.log('print object: ' + JSON.stringify(session));

Walter Caraza

보너스로 색상과 함께 Node.js를 사용하여 전체 개체를 인쇄하려면:

 console.dir(object, {depth: null, colors: true})

색상은 물론 선택 사항이며 '깊이: null'은 전체 개체를 인쇄합니다.

옵션은 브라우저에서 지원되지 않는 것 같습니다.

참조:

https://developer.mozilla.org/en-US/docs/Web/API/Console/dir

https://nodejs.org/api/console.html#console_console_dir_obj_options


jpoppe

내가 찾은 가장 간단하고 가장 좋은 방법은 이전에 말했듯이

 var getPrintObject=function(object) { return JSON.stringify(object); }

yonia

(이것은 GitHub의 내 라이브러리에 추가되었습니다)

여기에서 바퀴를 재발명하십시오! 이러한 솔루션 중 어느 것도 내 상황에 맞지 않았습니다. 그래서 나는 윌슨페이지 의 대답을 재빨리 조작했다. 이것은 화면에 인쇄하기 위한 것이 아닙니다(콘솔, 텍스트 필드 등을 통해). alert 에 대해 OP가 요청한 대로 잘 작동합니다. 여기에 있는 많은 답변은 OP가 요청한 대로 alert 어쨌든 데이터 전송용으로 포맷되어 있습니다. toSource() 와 매우 유사한 결과를 반환하는 것 같습니다. JSON.stringify 에 대해 테스트하지 않았지만 이것이 거의 같은 것이라고 가정합니다. 이 버전은 폴리필에 가깝기 때문에 어떤 환경에서도 사용할 수 있습니다. 이 함수의 결과는 유효한 Javascript 객체 선언입니다.

이와 같은 것이 이미 SO 어딘가에 있다면 의심의 여지가 없지만 과거 답변을 검색하는 데 시간을 보내는 것보다 만드는 것이 더 짧았습니다. 그리고 이 질문은 내가 이것에 대해 검색하기 시작했을 때 Google에서 가장 많이 검색된 것이었습니다. 여기에 올리는 것이 다른 사람들에게 도움이 될 수 있다고 생각했습니다.

어쨌든, 이 함수의 결과는 객체의 문자열 표현이 됩니다. 객체에 객체와 배열이 포함되어 있고 해당 객체나 배열에 객체와 배열이 더 포함되어 있더라도 마찬가지입니다. (술 좋아하신다고? 그래서 차에 쿨러로 뽀송뽀송 해주고, 쿨러에 쿨러로 뽀송뽀송. 그래서 쿨러가 시원하게 마실 수 있게.)

배열은 {} 대신 [] 로 저장되므로 키/값 쌍이 없고 값만 있습니다. 일반 배열처럼. 따라서 배열처럼 생성됩니다.

또한 모든 문자열(키 이름 포함)은 따옴표로 묶습니다. 이러한 문자열에 특수 문자(공백 또는 슬래시)가 없는 경우에는 필요하지 않습니다. 그러나 여전히 잘 작동하는 일부 인용문을 제거하기 위해 이것을 감지하고 싶지는 않았습니다.

이 결과 문자열은 eval 과 함께 사용하거나 문자열 조작을 통해 var에 덤프할 수 있습니다. 따라서 텍스트에서 개체를 다시 만듭니다.

 function ObjToSource(o){ if (!o) return 'null'; var k="",na=typeof(o.length)=="undefined"?1:0,str=""; for(var p in o){ if (na) k = "'"+p+ "':"; if (typeof o[p] == "string") str += k + "'" + o[p]+"',"; else if (typeof o[p] == "object") str += k + ObjToSource(o[p])+","; else str += k + o[p] + ","; } if (na) return "{"+str.slice(0,-1)+"}"; else return "["+str.slice(0,-1)+"]"; }

내가 모든 것을 망쳐 놓았는지 알려주십시오. 테스트에서 잘 작동합니다. array 을 감지하기 위해 생각할 수 있는 유일한 방법 length 가 있는지 확인하는 것이었습니다. Javascript는 실제로 배열을 객체로 저장하기 때문에 실제로 array 유형을 확인할 수 없습니다(그런 유형이 없습니다!). 다른 사람이 더 나은 방법을 알고 있다면 듣고 싶습니다. length 라는 속성도 있는 경우 이 함수는 실수로 이를 배열로 취급하기 때문입니다.

편집: null 값 개체에 대한 검사가 추가되었습니다. 감사합니다 브록 아담스

편집: 아래는 무한 재귀 개체를 인쇄할 수 있는 고정 기능입니다. toSource 가 무한 재귀를 한 번 인쇄하기 때문에 FF의 toSource 와 동일하게 인쇄하지 않습니다. 이 함수는 즉시 종료합니다. 이 함수는 위의 함수보다 느리게 실행되므로 위의 함수를 편집하는 대신 여기에 추가합니다. 이 함수는 어딘가에 다시 링크되는 개체를 전달할 계획인 경우에만 필요합니다.

 const ObjToSource=(o)=> { if (!o) return null; let str="",na=0,k,p; if (typeof(o) == "object") { if (!ObjToSource.check) ObjToSource.check = new Array(); for (k=ObjToSource.check.length;na<k;na++) if (ObjToSource.check[na]==o) return '{}'; ObjToSource.check.push(o); } k="",na=typeof(o.length)=="undefined"?1:0; for(p in o){ if (na) k = "'"+p+"':"; if (typeof o[p] == "string") str += k+"'"+o[p]+"',"; else if (typeof o[p] == "object") str += k+ObjToSource(o[p])+","; else str += k+o[p]+","; } if (typeof(o) == "object") ObjToSource.check.pop(); if (na) return "{"+str.slice(0,-1)+"}"; else return "["+str.slice(0,-1)+"]"; }

시험:

 var test1 = new Object(); test1.foo = 1; test1.bar = 2; var testobject = new Object(); testobject.run = 1; testobject.fast = null; testobject.loop = testobject; testobject.dup = test1; console.log(ObjToSource(testobject)); console.log(testobject.toSource());

결과:

 {'run':1,'fast':null,'loop':{},'dup':{'foo':1,'bar':2}} ({run:1, fast:null, loop:{run:1, fast:null, loop:{}, dup:{foo:1, bar:2}}, dup:{foo:1, bar:2}})

document.body 를 인쇄하려는 것은 끔찍한 예입니다. toSource 사용할 때 빈 객체 문자열을 출력합니다. 그리고 위의 기능을 사용할 때 SecurityError: The operation is insecure. . 그리고 Chrome은 Uncaught RangeError: Maximum call stack size exceeded 충돌합니다. 분명히 document.body 는 문자열로 변환되지 않았습니다. 너무 크거나 특정 속성에 액세스하기 위한 보안 정책에 위배되기 때문입니다. 내가 여기에서 뭔가를 망쳐 놓은 것이 아니라면 말하십시오!


Pimp Trizkit

전체 길이의 개체를 인쇄하려면 다음을 사용할 수 있습니다.

console.log(require('util').inspect(obj, {showHidden: false, 깊이: null})

객체를 문자열로 변환하여 인쇄하려면 다음을 수행하십시오.

console.log(JSON.stringify(obj));


sreepurna

방법은 다음과 같습니다.

 console.log("%o", obj);

Anton Harniakou

pagewil의 답변이 제공한 객체를 재귀적으로 인쇄하는 방법이 필요했습니다(감사합니다!). 특정 수준까지 인쇄하는 방법을 포함하고 현재 수준에 따라 적절하게 들여쓰기되도록 간격을 추가하여 더 읽기 쉽도록 약간 업데이트했습니다.

 // Recursive print of object var print = function( o, maxLevel, level ) { if ( typeof level == "undefined" ) { level = 0; } if ( typeof level == "undefined" ) { maxLevel = 0; } var str = ''; // Remove this if you don't want the pre tag, but make sure to remove // the close pre tag on the bottom as well if ( level == 0 ) { str = '<pre>'; } var levelStr = ''; for ( var x = 0; x < level; x++ ) { levelStr += ' '; } if ( maxLevel != 0 && level >= maxLevel ) { str += levelStr + '...</br>'; return str; } for ( var p in o ) { if ( typeof o[p] == 'string' ) { str += levelStr + p + ': ' + o[p] + ' </br>'; } else { str += levelStr + p + ': { </br>' + print( o[p], maxLevel, level + 1 ) + levelStr + '}</br>'; } } // Remove this if you don't want the pre tag, but make sure to remove // the open pre tag on the top as well if ( level == 0 ) { str += '</pre>'; } return str; };

용법:

 var pagewilsObject = { name: 'Wilson Page', contact: { email: 'wilson@hotmail.com', tel: '123456789' } } // Recursive of whole object $('body').append( print(pagewilsObject) ); // Recursive of myObject up to 1 level, will only show name // and that there is a contact object $('body').append( print(pagewilsObject, 1) );

megaboss98

ES6 템플릿 리터럴 개념을 사용하여 JavaScript 객체의 내용을 문자열 형식으로 표시할 수도 있습니다.

 alert(`${JSON.stringify(obj)}`); 

 const obj = { "name" : "John Doe", "habbits": "Nothing", }; alert(`${JSON.stringify(obj)}`);


Ritu

나는 항상 console.log("object will be: ", obj, obj1) 합니다. 이렇게 하면 JSON으로 stringify를 사용하여 해결 방법을 수행할 필요가 없습니다. 개체의 모든 속성이 멋지게 확장됩니다.


nils petersohn

콘솔 내에서 객체를 표시하는 또 다른 방법은 JSON.stringify 입니다. 아래 예를 확인하세요.

 var gandalf = { "real name": "Gandalf", "age (est)": 11000, "race": "Maia", "haveRetirementPlan": true, "aliases": [ "Greyhame", "Stormcrow", "Mithrandir", "Gandalf the Grey", "Gandalf the White" ] }; //to console log object, we cannot use console.log("Object gandalf: " + gandalf); console.log("Object gandalf: "); //this will show object gandalf ONLY in Google Chrome NOT in IE console.log(gandalf); //this will show object gandalf IN ALL BROWSERS! console.log(JSON.stringify(gandalf)); //this will show object gandalf IN ALL BROWSERS! with beautiful indent console.log(JSON.stringify(gandalf, null, 4));

Kean Amaral

자바스크립트 기능

 <script type="text/javascript"> function print_r(theObj){ if(theObj.constructor == Array || theObj.constructor == Object){ document.write("<ul>") for(var p in theObj){ if(theObj[p].constructor == Array || theObj[p].constructor == Object){ document.write("<li>["+p+"] => "+typeof(theObj)+"</li>"); document.write("<ul>") print_r(theObj[p]); document.write("</ul>") } else { document.write("<li>["+p+"] => "+theObj[p]+"</li>"); } } document.write("</ul>") } } </script>

인쇄 개체

 <script type="text/javascript"> print_r(JAVACRIPT_ARRAY_OR_OBJECT); </script>

자바스크립트에서 print_r을 통해


Mukesh Chapagain

var list = function(object) { for(var key in object) { console.log(key); } }

여기서 object 는 당신의 개체입니다

또는 크롬 개발 도구의 "콘솔" 탭에서 이것을 사용할 수 있습니다.

console.log(object);


user3632930

객체 obj = {0:'John', 1:'Foo', 2:'Bar'}

개체의 내용 인쇄

 for (var i in obj){ console.log(obj[i], i); }

콘솔 출력(Chrome DevTools):

 John 0 Foo 1 Bar 2

도움이 되기를 바랍니다!


codelox

console.table 을 사용하는 것을 선호하므로 다음 객체가 있다고 상상해 보십시오.

 const obj = {name: 'Alireza', family: 'Dezfoolian', gender: 'male', netWorth: "$0"};

그러면 아래와 같이 깔끔하고 읽기 쉬운 표가 보일 것입니다. 콘솔.테이블


Alireza

콘솔을 통한 간단하고 빠른 디버깅을 위해 프로젝트에서 항상 사용하는 작은 도우미 기능입니다. Laravel에서 영감을 얻었습니다.

 /** * @param variable mixed The var to log to the console * @param varName string Optional, will appear as a label before the var */ function dd(variable, varName) { var varNameOutput; varName = varName || ''; varNameOutput = varName ? varName + ':' : ''; console.warn(varNameOutput, variable, ' (' + (typeof variable) + ')'); }

용법

dd(123.55); 출력:
여기에 이미지 설명 입력

 var obj = {field1: 'xyz', field2: 2016}; dd(obj, 'My Cool Obj');

여기에 이미지 설명 입력


George Kagan

Node.js용 인라이너를 찾고 있다면...

 console.log("%o", object);

Rafael Xavier

나는 pagewil의 인쇄 방법을 사용했고 매우 잘 작동했습니다.

다음은 (조잡한) 들여쓰기와 고유한 prop/ob 구분 기호가 있는 약간 확장된 버전입니다.

 var print = function(obj, delp, delo, ind){ delp = delp!=null ? delp : "\t"; // property delimeter delo = delo!=null ? delo : "\n"; // object delimeter ind = ind!=null ? ind : " "; // indent; ind+ind geometric addition not great for deep objects var str=''; for(var prop in obj){ if(typeof obj[prop] == 'string' || typeof obj[prop] == 'number'){ var q = typeof obj[prop] == 'string' ? "" : ""; // make this "'" to quote strings str += ind + prop + ': ' + q + obj[prop] + q + '; ' + delp; }else{ str += ind + prop + ': {'+ delp + print(obj[prop],delp,delo,ind+ind) + ind + '}' + delo; } } return str; };

bitless

pagewils 코드의 또 다른 수정... 그의 것은 문자열 이외의 다른 것을 인쇄하지 않고 숫자 및 부울 필드를 공백으로 두었고 megaboss가 생성한 함수 바로 내부의 두 번째 typeof의 오타를 수정했습니다.

 var print = function( o, maxLevel, level ) { if ( typeof level == "undefined" ) { level = 0; } if ( typeof maxlevel == "undefined" ) { maxLevel = 0; } var str = ''; // Remove this if you don't want the pre tag, but make sure to remove // the close pre tag on the bottom as well if ( level == 0 ) { str = '<pre>'; // can also be <pre> } var levelStr = '<br>'; for ( var x = 0; x < level; x++ ) { levelStr += ' '; // all those spaces only work with <pre> } if ( maxLevel != 0 && level >= maxLevel ) { str += levelStr + '...<br>'; return str; } for ( var p in o ) { switch(typeof o[p]) { case 'string': case 'number': // .tostring() gets automatically applied case 'boolean': // ditto str += levelStr + p + ': ' + o[p] + ' <br>'; break; case 'object': // this is where we become recursive default: str += levelStr + p + ': [ <br>' + print( o[p], maxLevel, level + 1 ) + levelStr + ']</br>'; break; } } // Remove this if you don't want the pre tag, but make sure to remove // the open pre tag on the top as well if ( level == 0 ) { str += '</pre>'; // also can be </pre> } return str; };

ppetree

출처 : http:www.stackoverflow.com/questions/957537/how-can-i-display-a-javascript-object

반응형