다음과 같은 형식의 json 배열이 있습니다.
[{
"published": true,
"tags": ["tag1", "tag2"],
"categories": ["cat1"],
"author": "some name",
"post-format": "standard",
"title": "Second Post,",
"url-slug": "second-post",
"first-published-on": "2019-03-28",
"last-updated-on": "2019-03-28",
"meta": {
"title": "Second Post",
"description": "Second post."
},
"excerpt": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt",
"path": "2019/03/28/SecondPost.md"
}, {
"published": true,
"tags": ["tag1", "tag2", "tag3"],
"categories": ["cat1", "cat2"],
"author": "some name",
"post-format": "standard",
"title": "Getting Started",
"url-slug": "getting-started",
"first-published-on": "2019-03-20",
"last-updated-on": "2019-03-20",
"meta": {
"title": "Getting Started",
"description": "Getting started post."
},
"excerpt": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt",
"path": "2019/03/20/GettingStarted.md"
}]
아래 형식으로 태그별로 그룹화하고 싶습니다.
[{
"tag1": [{...}, {...}],
"tag2": [{...}, {...}],
"tag3": [{...}]
}]
lodash를 사용하여 그렇게하려고했습니다.
const groupedByTag = _.groupBy(blogMetadata, function(postmetadata) {
postmetadata.tags.map(tag => {
return tag
})
})
분명히 위의 코드는 올바르지 않으며 작동하지 않습니다. 많은 진전없이 관련 게시물 을 살펴 보았습니다 . 도움을 주시면 감사하겠습니다.
reduce
& forEach
를 대신 사용할 수 있습니다 loadash
. 내부 감소 콜백 함수 는이 이름으로 tags
존재하는 경우 누산기 객체를 반복 하고 확인합니다 key
. 존재한다면 현재 객체를 푸시하고 그렇지 않으면 생성 key
하고 푸시합니다.value
let data = [{
"published": true,
"tags": ["tag1", "tag2"],
"categories": ["cat1"],
"author": "some name",
"post-format": "standard",
"title": "Second Post,",
"url-slug": "second-post",
"first-published-on": "2019-03-28",
"last-updated-on": "2019-03-28",
"meta": {
"title": "Second Post",
"description": "Second post."
},
"excerpt": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt",
"path": "2019/03/28/SecondPost.md"
}, {
"published": true,
"tags": ["tag1", "tag2", "tag3"],
"categories": ["cat1", "cat2"],
"author": "some name",
"post-format": "standard",
"title": "Getting Started",
"url-slug": "getting-started",
"first-published-on": "2019-03-20",
"last-updated-on": "2019-03-20",
"meta": {
"title": "Getting Started",
"description": "Getting started post."
},
"excerpt": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt",
"path": "2019/03/20/GettingStarted.md"
}];
let newMapped = [data.reduce(function(acc, curr) {
curr.tags.forEach(function(item) {
if (acc[item]) {
acc[item].push(curr)
} else {
acc[item] = [curr]
}
})
return acc;
}, {})];
console.log(newMapped)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다