객체(트리)를 반복적으로 순환하기
(jQuery 또는 JavaScript에서) 각 개체를 루프할 수 있는 방법이 있습니까? 그리고 그것은 자녀 및 손자녀 등입니다.
그렇다면...그들의 이름도 읽을 수 있습니까?
예:
foo :{
bar:'',
child:{
grand:{
greatgrand: {
//and so on
}
}
}
}
그래서 루프는 이런 일을 해야 합니다.
loop start
if(nameof == 'child'){
//do something
}
if(nameof == 'bar'){
//do something
}
if(nameof =='grand'){
//do something
}
loop end
루프를 찾고 있습니다.
for (var key in foo)
{
if (key == "child")
// do something...
}
알아두시기 바랍니다.for...in
루프는 개체의 프로토타입에 추가된 속성을 포함하여 열거 가능한 속성 위에서 반복됩니다.이러한 속성에 대한 작업을 방지하려면 다음을 사용할 수 있습니다.hasOwnProperty
속성이 해당 개체에만 속하는지 확인하는 방법:
for (var key in foo)
{
if (!foo.hasOwnProperty(key))
continue; // skip this property
if (key == "child")
// do something...
}
반복 루프를 반복적으로 수행하는 것은 재귀 함수를 작성하는 것만큼 간단할 수 있습니다.
// This function handles arrays and objects
function eachRecursive(obj)
{
for (var k in obj)
{
if (typeof obj[k] == "object" && obj[k] !== null)
eachRecursive(obj[k]);
else
// do something...
}
}
속성 실행 함수와 함께 객체 루프 재귀 함수를 가질 수 있습니다.propExec
그 안에 내장된.
function loopThroughObjRecurs (obj, propExec) {
for (var k in obj) {
if (typeof obj[k] === 'object' && obj[k] !== null) {
loopThroughObjRecurs(obj[k], propExec)
} else if (obj.hasOwnProperty(k)) {
propExec(k, obj[k])
}
}
}
여기서 테스트:
// I use the foo object of the OP
var foo = {
bar:'a',
child:{
b: 'b',
grand:{
greatgrand: {
c:'c'
}
}
}
}
function loopThroughObjRecurs (obj, propExec) {
for (var k in obj) {
if (typeof obj[k] === 'object' && obj[k] !== null) {
loopThroughObjRecurs(obj[k], propExec)
} else if (obj.hasOwnProperty(k)) {
propExec(k, obj[k])
}
}
}
// then apply to each property the task you want, in this case just console
loopThroughObjRecurs(foo, function(k, prop) {
console.log(k + ': ' + prop)
})
관계 트리를 다시 가져오려면 개체를 사용할 수 있습니다.키를 재귀적으로 누릅니다.
function paths(item) {
function iter(r, p) {
var keys = Object.keys(r);
if (keys.length) {
return keys.forEach(x => iter(r[x], p.concat(x)));
}
result.push(p);
}
var result = [];
iter(item, []);
return result;
}
var data = {
foo: {
bar: '',
child: {
grand: {
greatgrand: {}
}
}
}
};
console.log(paths(data));
함수와 일치하는 개체 구조 내의 값을 검색하도록 확장할 수 있습니다.
function objectSearch(rootItem, matcher) {
const visited = [];
const paths = [];
function iterate(item, path) {
if (visited.includes(item)) {
return;
}
visited.push(item);
if (typeof item === "object" && item !== null) {
var keys = Object.keys(item);
if (keys.length) {
return keys.forEach(key => iterate(item[key], path.concat(key)));
}
}
if (matcher(item)) {
paths.push(path);
}
}
iterate(rootItem, []);
return paths;
}
function searchForNaNs(rootItem) {
return objectSearch(rootItem, (v) => Object.is(NaN, v));
}
var banana = {
foo: {
bar: "",
child: {
grand: {
greatgrand: {},
nanan: "NaN",
nan: NaN,
},
},
},
};
console.log("There's a NaN at", searchForNaNs(banana)[0].join("."), "in this object:", banana);
개체 검색을 사용해 보십시오.이것은 머리를 감싸면 데이터 처리에 강력한 성능을 자랑합니다.
한 가지 좋은 점은 항목이 "안전 삭제" 순서로 이동된다는 것입니다.그래서 하나를 삭제해도 루프가 흐트러지지 않습니다.그리고 여러분은 부모님 등과 같은 많은 다른 재산들에 접근할 수 있습니다.
// const objectScan = require('object-scan');
const obj = { foo: { bar: '', child: { grand: { greatgrand: { /* and so on */ } } } } };
objectScan(['**'], {
filterFn: ({ property }) => {
console.log(property);
}
})(obj);
// => greatgrand
// => grand
// => child
// => bar
// => foo
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan@13.8.0"></script>
고지 사항:저는 물체 스캔의 저자입니다.
저는 신드레소르후스의 지도-obj & 필터-obj 유틸리티를 사용하는 것을 추천합니다.
언급URL : https://stackoverflow.com/questions/2549320/looping-through-an-object-tree-recursively
'it-source' 카테고리의 다른 글
단편에 비해 몇 가지 활동이 있습니까? (0) | 2023.08.19 |
---|---|
Angular JS로 CORS를 설정하려면 어떻게 해야 합니까? (0) | 2023.08.19 |
X-Powered-By 헤더를 제거할 수 없습니다.표현 (0) | 2023.08.19 |
끌어오기 요청을 Github의 기본값이 아닌 다른 분기에 병합 (0) | 2023.08.19 |
수행 표시줄과 새로 도입된 도구 모음의 차이점은 무엇입니까? (0) | 2023.08.19 |