[英]Removing levels in nested objects in JavaScript
我使用的 REST API 返回以下數據格式:
const documents = [
{
"fields": {
"title": {
"stringValue": "77"
},
"difficulty": {
"doubleValue": 77
},
},
"createTime": "2020-04-10T15:13:47.074204Z"
},
{
"fields": {
"title": {
"stringValue": "99"
},
"difficulty": {
"doubleValue": 99
},
},
"createTime": "2020-04-10T15:13:47.074204Z"
}
]
我需要的是這種格式:
{
title: "77",
difficulty: 77
},
{
title: "99",
difficulty: 99
}
這意味着我不僅要對這些數據進行分組,還要完全刪除中間的兩層。 我怎么做?
作為獎勵:我如何在這方面做得更好? 有什么好的資源嗎?
通過使用.map()
和解構如下:
const documents = [{ "fields": { "title": { "stringValue": "77" }, "difficulty": { "doubleValue": 77 }, }, "createTime": "2020-04-10T15:13:47.074204Z", }, { "fields": { "title": { "stringValue": "99" }, "difficulty": { "doubleValue": 99 }, }, "createTime": "2020-04-10T15:13:47.074204Z" } ]; const result = documents.map(({fields}) => ({title: fields.title.stringValue, difficulty: fields.difficulty.doubleValue})); console.log(result);
我希望這有幫助!
您可以使用Array#map
方法和Object.values
方法來實現結果。
const documents = [{ "fields": { "title": { "stringValue": "77" }, "difficulty": { "doubleValue": 77 }, }, "createTime": "2020-04-10T15:13:47.074204Z" }, { "fields": { "title": { "stringValue": "99" }, "difficulty": { "doubleValue": 99 }, }, "createTime": "2020-04-10T15:13:47.074204Z" } ] const result = documents.map(({ fields: { title: t, difficulty: d } }) => ({ title: Object.values(t)[0], difficulty: Object.values(d)[0] })); console.log(result);
您必須遍歷數據並選擇您的字段。 一種描述性的方法是使用 arrays 上提供的map()
function。
const documents = [ { "fields": { "title": { "stringValue": "77" }, "difficulty": { "doubleValue": 77 }, }, "createTime": "2020-04-10T15:13:47.074204Z" }, { "fields": { "title": { "stringValue": "99" }, "difficulty": { "doubleValue": 99 }, }, "createTime": "2020-04-10T15:13:47.074204Z" } ] let result = documents.map(document => ({ title: document.fields.title.stringValue, difficulty: document.fields.difficulty.doubleValue })); console.log(result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.