【问题标题】:Convert array of objects inside in object into array of properties将对象中的对象数组转换为属性数组
【发布时间】:2022-12-08 01:06:25
【问题描述】:

我有一个对象,它有一些像这样的属性:

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;

【问题讨论】:

  • 是什么让你的方法“丑陋”?
  • 您的解决方案非常好。
  • 忘记命名我只是在测试,但它很长,我想知道是否有一个简单而简短的解决方案。

标签: javascript angular typescript


【解决方案1】:

我们循环数组并使用 Object.assign() 方法将对象数组转换为单个对象。这会将每个对象合并为一个结果对象。

Object.assign() 方法还将一个或多个对象的属性合并到一个对象中。

【讨论】:

    【解决方案2】:

    您可以使用传播运算符和地图

    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),
    })

    【讨论】:

      猜你喜欢
      • 2019-02-10
      • 1970-01-01
      • 2019-06-05
      • 1970-01-01
      • 2016-03-22
      • 1970-01-01
      • 2020-05-14
      • 1970-01-01
      相关资源
      最近更新 更多