如何从现有对象数据生成以名称为键的新对象?
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

