typescript 将in object中的对象数组转换为属性数组

bzzcjhmw  于 2022-12-14  发布在  TypeScript
关注(0)|答案(2)|浏览(297)

我有一个对象,它有如下一些属性:

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": "",
        },
    ],
}

我想将对象中的对象数组(operationIdsratingIds)转换为属性数组,我正在接收这个对象,我想对它应用更改并提供另一个方法,因此它应该如下所示:

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;
0kjbasz6

0kjbasz61#

可以使用扩散运算符和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),
})

作为一种功能

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)
wsxa1bj1

wsxa1bj12#

我们循环数组,并使用Object.assign()方法将一个对象数组转换为一个对象,这将每个对象合并为一个结果对象。
Object.assign()方法还可以将一个或多个对象的属性合并到单个对象中。

相关问题