我有一個具有特定結構的 JSON 檔案(請參閱樹),但我也需要它的結構類似于預期的輸出。
是否可以在 JS 中重新組織資料?如果是這樣,你會怎么做?我需要幫助來重組或將樹映射到預期的輸出。我希望你們能幫助我解決這個重組問題。
const tree = [
{
"type": "object",
"name": "pets",
"child":
[
{
type: "array",
name: "properties",
"child":
[
{
type: "object",
name: "PK",
},
{
type: "object",
name: "PO",
},
{
type: "object",
name: "PS",
},
{
type: "object",
name: "PA",
child: [{type: "array", name: "list"}, ]
},
]
},
{
type: "object",
name: "get",
}
]
},
]
const expectedResult = [
{
pets:
{
properties:
[
{
name: "PK"
},
{
name: "PO"
},
{
name: "PS"
},
{
"PA" :
{
list: []
}
}
],
get: {}
}
},
]
uj5u.com熱心網友回復:
您可以為各種型別及其功能獲取一個物件,以構建映射子項所需的結構。
const
tree = [{ type: "object", name: "pets", child: [{ type: "array", name: "properties", child: [{ type: "object", name: "PK" }, { type: "object", name: "PO" }, { type: "object", name: "PS" }, { type: "object", name: "PA", child: [{ type: "array", name: "list" }] }] }, { type: "object", name: "get" }] }],
types = {
object: (name, child) => child
? { [name]: Object.assign({}, ...child.map(fn)) }
: { name: name },
array: (name, child = []) => ({ [name]: child.map(fn) })
},
fn = ({ type, name, child }) => types[type](name, child),
result = tree.map(fn);
console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
uj5u.com熱心網友回復:
- 決議你的 json 資料
https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
- 映射資料以滿足您的需求
https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Array/map
(或遍歷它,無論對您有用)
uj5u.com熱心網友回復:
首先,我是小姐,不是先生??
好吧,這是一個詳細的示例,這不是最佳實踐,但我認為這是更容易理解的方法。
// First create an empty array to store your results.
let expectedResults = [];
// Loop through you tree object
for (let i in tree) {
// create empty object for each tree object
let treeObj = {};
// get the name of the object
const objName = tree[i]['name'];
// assign it as a key and set it's value as object
treeObj[objName] = {};
// get the children
const objChild = tree[i]['child'];
// loop through the children
for (let j in objChild) {
// get the name
const childName = objChild[j].name;
// check the type and assign either as object either as array
if (objChild[j].type === 'object') {
treeObj[objName][childName] = {};
}
if (objChild[j].type === 'array') {
treeObj[objName][childName] = [];
const childArr = objChild[j].child;
for (let k in childArr) {
if (childArr[k].type === 'object') {
treeObj[objName][childName].push({
name: childArr[k].name
});
}
if (childArr[k].type === 'array') {
// and so on
}
}
}
}
expectedResults.push(treeObj);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/463022.html
標籤:javascript 反应 json 树
