javascript - 如何转换以属性值作为键的对象结构?
问题描述
例如我有这个对象:
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"]
解决方案
由于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; }
推荐阅读
- python - 如何从 OrderedDict 中提取特定值?
- android - Android - 约束布局 - 文本和图标的对齐方式
- powerbi - Power BI - 有条件的 DistinctCount 不起作用
- reactjs - 如何在使用 map() 函数时将 this.props 从父组件传递给子组件而不会未定义?
- algorithm - 将问题划分为 n^(1/2) 个子问题的递归算法的时间复杂度
- node.js - 如何为 Node.js、express、ejs 路由构建外部 API 调用?
- angular - 如何修复无法读取角度数据表上未定义的属性“长度”
- r - 不能在 R 中使用以数字命名的变量
- sorting - Dart 自定义列表排序
- erlang - 如何与不是 gen_servers 的工作人员一起运行主管?