首页 > 解决方案 > 如何转换以属性值作为键的对象结构?

问题描述

例如我有这个对象:

let obj = { id: "12", name: "abc" };

我需要把这个 obj 改成这样:

{ "12": "abc" }; // the key is the value of “id”

这样,我将能够通过 id 访问名称,如下所示:

let name = obj["12"];

编辑:

我需要转换以下对象:

 obj = {
        "groups": [{
                "groupId": 2345,
                "status": 2
            }, {
                "groupId": 3456,
                "status": 5
            }
        ]
     }

到:

obj ={
        "2345":2,
        "3456":5
    }

这将允许我使用groupId. 例如:要获得状态 5,我可以这样查看obj["2345"]

标签: javascriptarraysobjectdata-structuresmerge

解决方案


由于OP可以直接将groups数组项解析/展平为目标对象/结构...从...

{
  groups: [{
    groupId: 2345,
    status: 2,
  }, {
    groupId: 3456,
    status: 5,
  }],
}

... 进入 ...

{
  "2345": 2,
  "3456": 5
}

...一个函数可能会实现一种基于两者的方法,Array.prototype.reduce并且Object.assign对于每次迭代,该方法确实通过新的键值对聚合目标对象,并且相应的数据 ( groupId, status) 由迭代groups数组的每个项目传递。最后返回target的对象是 reducer 函数的累加器,最初作为简单的空对象字面量提供{}

上述方法有两种实现方式。第一个 ... resolveGroupsVerbose... 初学者可能更容易阅读/理解,因为代码明确说明了所做的事情,第二种方法 ... resolveGroups ... 使用解构赋值,从而产生更紧凑的代码.. .

// One and the same approach ...

// ... without any destructuring and destructuring assignments.
function resolveGroupsVerbose(value) {
  return value.groups.reduce((target, groupsItem) => {

    // create new object ...
    const obj = {};

    // ... and assign new key-value data
    //     derived from `groupsItem`.
    obj[groupsItem.groupId] = groupsItem.status;

    // return the aggregated target.
    return Object.assign(target, obj);

  } , {});
}

// ... with destructuring assignments.
function resolveGroups({ groups }) {
  return groups
    .reduce((target, { groupId, status }) =>
      Object.assign(target, { [groupId]: status }), {}
    );
}

const sample = {
  groups: [{
    groupId: 2345,
    status: 2,
  }, {
    groupId: 3456,
    status: 5,
  },
]};

console.log(
  'resolveGroupsVerbose(sample) ...',
  resolveGroupsVerbose(sample)
);
console.log(
  'resolveGroups(sample) ...',
  resolveGroups(sample)
);

// expected:  resolveGroups(sample) ... {
//   "2345": 2,
//   "3456": 5
// }
.as-console-wrapper { min-height: 100%!important; top: 0; }


推荐阅读