我有一個創建的對象數組,我想將其轉換爲嵌套屬性模板對象。嵌套對象將根據檢查的項目創建。將對象的嵌套數組轉換爲嵌套屬性模板對象
對象的第一級將其「checked」鍵設置爲null,因爲它們將始終添加爲屬性模板對象的開頭。
如果第一級對象有沒有屬性,或任何屬性的檢查,那麼就應該是這樣的:
{staff: true}
但是,如果對象具有屬性和一些屬性進行檢查,它看起來就像這樣:
{staffedLocation: ['schedulingGroup',
{property: 'staff', subProperties: ['description']}
]
}
這是一個非常簡單的例子,在某些情況下,嵌套對象的數組可以去進一步下跌,所以我知道我需要創建一個遞歸函數。然而,當我的對象的第一層完全不同於其餘部分時,我得到了如何去遞歸地創建它的問題。
手頭對象數組的一個例子是這樣的:
[
{checked: null, name: "staffedLocation", properties: [
{checked: null, name: "oid", properties: null, toggle: null, type: "integer"},
{checked: null, name: "_class", properties: null, toggle: null, type: "string"},
{checked: true, name: "schedulingGroups", properties: null, toggle: null, type: "list"},
{checked: null, name: "staff", properties: [
{checked: null, name: "oid", properties: null, toggle: null, type: "integer"},
{checked: null, name: "_class", properties: null, toggle: null, type: "string"},
{checked: true, name: "description", properties: null, toggle: null, type: "string"},
{checked: null, name: "limits", properties: null, toggle: null, type: "list"},
{checked: null, name: "weeklyMaxHours", properties: null, toggle: null, type: "integer"}
], toggle: true, type: "list"},
], toggle: true, type: "staffedLocation"},
{checked: null,
name: "staff", properties: [
{checked: null, name: "oid", properties: null, toggle: null, type: "integer"},
{checked: null, name: "_class", properties: null, toggle: null, type: "string"},
{checked: null, name: "description", properties: null, toggle: null, type: "string"},
{checked: null, name: "limits", properties: null, toggle: null, type: "list"},
{checked: null, name: "weeklyMaxHours", properties: null, toggle: null, type: "integer"}
], toggle: true, type: "staff"},
{checked: null, name: "assignedShifts", properties: null, toggle: null, type: "shiftForEmail"},
{checked: null, name: "editedShifts", properties: null, toggle: null, type: "shiftForEmail"},
{checked: null, name: "deletedShifts", properties: null, toggle: null, type: "shiftForEmail"},
{checked: null, name: "unassignedShifts", properties: null, toggle: null, type: "shiftForEmail"},
{checked: null, name: "rangeStart", properties: null, toggle: null, type: "timestamp"},
{checked: null, name: "rangeEnd", properties: null, toggle: null, type: "timestamp"}
]
而且我想它,然後被轉換成一個嵌套的對象,像這樣:
{
staffedLocation: ['schedulingGroup',{property: 'staff',subProperties: ['description']}],
staff: true,
assignedShifts: true,
editedShifts: true,
deletedShifts: true,
unassignedShifts: true,
rangeStart: true,
rangeEnd: true
}
如果第一個級別與其他級別不同,那麼在遍歷第一級時應執行遞歸函數。 [數組'map'方法](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)可用於循環。 – estus