我有一個這樣的物件:
const obj = {
"id": 5,
"adress": "Test"
"name": "Q1",
"sections": [
{
"code": "S1",
"label": "LS1",
"subSections": [ //I can have this level, or not
{
"code": "S1-1",
"label": 'LS1-1',
"questions": [ // If not, I will have this level instend
{
"code": "Q1",
"label": "LQ1",
"answer": [
{
"code": "A1",
"label": 'LA1',
}
],
}
]
}
],
}
]
}
我想創建一個新的 obj 但只有一些簡單的屬性,沒有陣列:
newObj = {
"id": 5,
"adress": "Test"
"name": "Q1",
}
挑戰在于以動態形式創建新物件,因此如果第一個物件更改為具有名為 Date 的新屬性,則新物件必須是:
const newObj = {
"id": 5,
"adress": "Test",
"date": "somedate",
"name": "Q1",
}
uj5u.com熱心網友回復:
為了避免對簡單(或其他)屬性的名稱進行硬編碼,您可以提取當前物件的所有條目,typeof用于過濾掉那些值不是簡單資料型別的條目,然后從這些條目中創建一個新物件。
Object.fromEntries(Object.entries(obj).filter(([prop, val]) => typeof(val) != 'object'))
uj5u.com熱心網友回復:
您可以使用擴展運算子,它將復制整個物件,并使用洗掉運算子洗掉您希望洗掉的部分物件。
const obj = {
"id": 5,
"adress": "Test",
"name": "Q1",
"sections": [
{
"code": "S1",
"label": "LS1",
"subSections": [ //I can have this level, or not
{
"code": "S1-1",
"label": 'LS1-1',
"questions": [ // If not, I will have this level instend
{
"code": "Q1",
"label": "LQ1",
"answer": [
{
"code": "A1",
"label": 'LA1',
}
],
}
]
}
],
}
]
}
const newObj = {...obj};
delete newObj.sections;
console.log(newObj); // {id: 5, address: 'Test', name: 'Q1'}
uj5u.com熱心網友回復:
您可以像這樣解構物件并省略您不想要的屬性。例如:
const { sections, ...newObj } = obj;
這是迄今為止最簡單的方法。它將創建一個名為 section 的變數并將所有其他屬性放入newObj其中,但是通常不認為創建這樣的未使用變數是好的做法。
如果您不介意undefined物件中的sections屬性值,您也可以使用Object.assign():
const newObj = Object.assign({}, obj, {
sections: undefined
})
最后的選擇是遍歷屬性:
const newObj = {};
for (const key of Object.keys(obj)) {
if (key === 'sections') {
continue;
}
newObj[key] = obj[key];
}
請注意,在所有這 3 個示例中,您只是制作了物件的淺表副本。意思是,雖然它newObj是一個新物件,但如果它們不是原始型別(例如字串、數字、布林值等),它們內部的值將參考obj物件內部的相同實體。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/510427.html
