【问题标题】:How to transform an object structure where a property value is going to serve as key?如何转换以属性值作为键的对象结构?
【发布时间】:2021-10-23 09:31:33
【问题描述】:

例如我有这个对象:

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

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

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

这样,我就可以通过 id 访问 name,如下所示:

let name = obj["12"];

编辑:

我需要转换以下对象:

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

收件人:

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

这将使我可以使用groupId 轻松查找状态。 例如:要获得状态5,我可以这样看obj["2345"]

【问题讨论】:

  • obj = {[obj.id]:obj.name}
  • OP 是否正在寻找一种可以处理嵌套数据结构的通用递归工作方法?因为提供的示例的解决方案应该不难由 OP 自己提出。
  • 如果你只有一个对象,为什么需要通过它的id来访问它的名字呢?或者你实际上有多个对象(例如在一个数组中)?那么请edit你的问题包含实际的数据结构。
  • 你需要提供更多关于为什么你不能这样做的信息这里没有问题

标签: javascript arrays object data-structures merge


【解决方案1】:

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

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

...进入...

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

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

上述方法有两种实现方式。第一个 ... resolveGroupsVerbose ... 初学者可能更容易阅读/理解,因为代码明确说明了所做的事情,第二种方法 ... resolveGroups ... 使用 Destructuring assignments 导致在更紧凑的代码中...

// 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; }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-14
    • 2020-08-03
    • 2022-11-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-17
    • 1970-01-01
    • 2011-04-30
    相关资源
    最近更新 更多