You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从现有对象数据生成以名称为键的新对象?

Convert peopleObject to peopleByNames

Got it, let's break down how to transform your original object into the desired peopleByNames structure. There are a couple of clean ways to do this in JavaScript, depending on your preference for modern syntax or straightforward, readable loops.

Method 1: Using a for...in loop (great for readability)

This is a simple approach that works in all JavaScript environments, making it easy for anyone to follow:

var peopleObject = { "123": { id: 123, name: "dave", age: 23 }, "456": { id: 456, name: "chris", age: 23 } };
var peopleByNames = {};

for (const key in peopleObject) {
  const person = peopleObject[key];
  peopleByNames[person.name] = person.id;
}

console.log(peopleByNames); // { "dave": 123, "chris": 456 }

Method 2: Using Object.entries() and reduce() (modern, functional approach)

If you prefer concise, modern JavaScript, this approach leverages array methods to build the new object in a more declarative way:

var peopleObject = { "123": { id: 123, name: "dave", age: 23 }, "456": { id: 456, name: "chris", age: 23 } };

var peopleByNames = Object.entries(peopleObject).reduce((acc, [_, person]) => {
  acc[person.name] = person.id;
  return acc;
}, {});

console.log(peopleByNames); // { "dave": 123, "chris": 456 }

Here, Object.entries() converts the original object into an array of [key, value] pairs. We then use reduce() to iterate over these pairs, building our new object by mapping each person's name to their ID. The underscore _ is just a convention for a variable we don't need to use.

Important Edge Case Note:

If your original object has multiple people with the same name, the last entry processed (either in the loop or reduce) will overwrite any previous entries with that name in peopleByNames. Keep this in mind if duplicate names are a possibility in your dataset!

内容的提问来源于stack exchange,提问作者neverrmind

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:15:34