[英]Convert array of objects inside in object into array of properties
我有一個 Object,它有一些像這樣的屬性:
obj1={
"id": 2,
"description": "",
"operationIds": [
{
"id": 1,
"name": "Standard"
}
],
"ratingIds": [
{
"id": 1,
"name": "name1",
"description": "",
},
{
"id": 4,
"name": "name4",
"description": "",
},
{
"id": 8,
"name": "name8",
"description": "",
},
],
}
我想將 object 中的對象數組( operationIds
和ratingIds
)隱藏到屬性數組中,我收到這個 object 並且我想對其應用更改並提供另一種方法,因此它應該如下所示:
obj1={
"id": 2,
"description": "",
"operationIds": [
1
],
"ratingIds": [
1,
4,
8
],
"timestamp": "AAAAAAAGJ6c=",
"estimatedUtilReconciliationApplies": true
}
我能夠做到,但是以一種非常丑陋的方式,有沒有更簡單明了的方法來完成這個?
let x = {...obj} as any;
let ar1 = x.operationIds;
const arr1= ar1.map(function (obj) {
return obj.id;
});
let ar2 = x.ratingIds;
const arr2= ar2.map(function (obj) {
return obj.id;
});
x.operatingEnvironmentIds = arr1;
x.thrustRatingIds = arr2;
您可以使用傳播運算符和 map
let obj1={ "id": 2, "description": "", "operationIds": [ { "id": 1, "name": "Standard" } ], "ratingIds": [ { "id": 1, "name": "name1", "description": "", }, { "id": 4, "name": "name4", "description": "", }, { "id": 8, "name": "name8", "description": "", }, ], } console.log({...obj1, operationIds:obj1.operationIds.map(elem => elem.id), ratingIds:obj1.ratingIds.map(elem => elem.id), })
作為 function
let obj1={ "id": 2, "description": "", "operationIds": [ { "id": 1, "name": "Standard" } ], "ratingIds": [ { "id": 1, "name": "name1", "description": "", }, { "id": 4, "name": "name4", "description": "", }, { "id": 8, "name": "name8", "description": "", }, ], } let transform = (obj) => { return({...obj, operationIds:obj.operationIds.map(elem => elem.id), ratingIds:obj.ratingIds.map(elem => elem.id), }) } let transformed = transform(obj1) console.log(transformed)
我們循環數組並使用 Object.assign() 方法將對象數組轉換為單個 object。這會將每個 object 合並為一個結果 object。
Object.assign() 方法還將一個或多個對象的屬性合並到一個 object 中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.