The Object.entries() method translates this sentence into English.
Basic Concept of the Object.entries() Method
Object.entries()
is a static method introduced in ECMAScript 2017 (ES8) that returns an array of key-value pairs for a given object's own enumerable properties. This method provides a concise way to traverse an object's properties and values, addressing the limitations of earlier approaches that required combining Object.keys()
with for...in
loops.
const obj = { a: 1, b: 2, c: 3 };
console.log(Object.entries(obj));
// Output: [ ['a', 1], ['b', 2], ['c', 3] ]
Method Syntax and Parameters
The syntax of Object.entries()
is very simple:
Object.entries(obj)
It accepts one parameter:
obj
: The object whose own enumerable property key-value pairs are to be returned.
The return value is an array whose elements are arrays corresponding to the enumerable property key-value pairs found directly on obj
. The order of the key-value pairs in the array is the same as that provided by a for...in
loop.
Comparison with Related Methods
Difference from Object.keys()
Object.keys()
only returns an array of an object's keys, while Object.entries()
returns an array of key-value pairs:
const user = { name: 'Alice', age: 25 };
console.log(Object.keys(user)); // ['name', 'age']
console.log(Object.entries(user)); // [ ['name', 'Alice'], ['age', 25] ]
Relationship with Object.values()
Object.values()
is the "other half" of Object.entries()
, as it only returns the values:
const user = { name: 'Bob', age: 30 };
console.log(Object.values(user)); // ['Bob', 30]
console.log(Object.entries(user)); // [ ['name', 'Bob'], ['age', 30] ]
Practical Use Cases
Converting Objects to Maps
Object.entries()
can conveniently convert a plain object to a Map:
const obj = { foo: 'bar', baz: 42 };
const map = new Map(Object.entries(obj));
console.log(map); // Map { 'foo' => 'bar', 'baz' => 42 }
Iterating Over Object Properties
More concise than traditional for...in
loops:
const person = { name: 'John', age: 30, city: 'New York' };
// Traditional approach
for (const key in person) {
console.log(`${key}: ${person[key]}`);
}
// Using Object.entries()
for (const [key, value] of Object.entries(person)) {
console.log(`${key}: ${value}`);
}
Filtering and Transforming Objects
Combined with array methods, it enables complex object operations:
const prices = { apple: 1.2, banana: 0.8, orange: 1.5 };
// Filter fruits with prices greater than 1
const expensiveFruits = Object.entries(prices)
.filter(([fruit, price]) => price > 1)
.reduce((acc, [fruit, price]) => {
acc[fruit] = price;
return acc;
}, {});
console.log(expensiveFruits); // { apple: 1.2, orange: 1.5 }
Handling Special Object Cases
Non-Object Parameters
If the parameter is not an object, it will be coerced into one:
console.log(Object.entries('foo'));
// [ ['0', 'f'], ['1', 'o'], ['2', 'o'] ]
Non-Enumerable Properties
Object.entries()
does not return non-enumerable properties:
const obj = Object.create({}, {
foo: { value: 1, enumerable: true },
bar: { value: 2, enumerable: false }
});
console.log(Object.entries(obj)); // [ ['foo', 1] ]
Prototype Chain Properties
It does not return properties from the prototype chain:
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function() {};
const person = new Person('Alice');
console.log(Object.entries(person)); // [ ['name', 'Alice'] ]
Performance Considerations
While Object.entries()
offers convenience, note the following in performance-sensitive scenarios:
- It creates a new array containing all key-value pairs.
- For large objects, this may cause memory pressure.
- In frequently called hot paths, alternative methods may be preferable.
Browser Compatibility and Polyfill
Object.entries()
is supported in most modern browsers, but for older environments, the following polyfill can be used:
if (!Object.entries) {
Object.entries = function(obj) {
const ownProps = Object.keys(obj);
let i = ownProps.length;
const resArray = new Array(i);
while (i--) {
resArray[i] = [ownProps[i], obj[ownProps[i]]];
}
return resArray;
};
}
Integration with Other ES Features
Combined with Destructuring Assignment
const user = { id: 1, name: 'Charlie', role: 'admin' };
// Extract specific properties only
const [[, name], [, role]] = Object.entries(user);
console.log(name, role); // 'Charlie' 'admin'
Combined with Spread Operator
const defaults = { color: 'red', size: 'medium' };
const custom = { size: 'large', weight: 'heavy' };
const combined = Object.entries({ ...defaults, ...custom })
.reduce((acc, [key, value]) => {
acc[key] = value;
return acc;
}, {});
console.log(combined);
// { color: 'red', size: 'large', weight: 'heavy' }
Usage in React
In React, Object.entries()
can be used for dynamic component rendering:
function UserProfile({ user }) {
return (
<div>
{Object.entries(user).map(([key, value]) => (
<div key={key}>
<strong>{key}:</strong> {value}
</div>
))}
</div>
);
}
const user = { name: 'Diana', age: 28, occupation: 'Engineer' };
ReactDOM.render(<UserProfile user={user} />, document.getElementById('root'));
Handling Symbol Properties
Object.entries()
does not return Symbol properties:
const obj = {
[Symbol('secret')]: 'hidden',
normal: 'visible'
};
console.log(Object.entries(obj)); // [ ['normal', 'visible'] ]
To retrieve Symbol properties, use Object.getOwnPropertySymbols()
:
const symbolProps = Object.getOwnPropertySymbols(obj)
.map(sym => [sym, obj[sym]]);
console.log(symbolProps); // [ [Symbol(secret), 'hidden'] ]
Usage in Node.js Environment
In Node.js, Object.entries()
is equally useful, often for handling module exports or configuration objects:
const config = {
port: 3000,
db: {
host: 'localhost',
name: 'test'
},
logging: true
};
// Flatten the configuration
const flatConfig = {};
Object.entries(config).forEach(([key, value]) => {
if (typeof value === 'object') {
Object.entries(value).forEach(([subKey, subValue]) => {
flatConfig[`${key}.${subKey}`] = subValue;
});
} else {
flatConfig[key] = value;
}
});
console.log(flatConfig);
/*
{
port: 3000,
'db.host': 'localhost',
'db.name': 'test',
logging: true
}
*/
Interaction with JSON
Object.entries()
is particularly useful when working with JSON data:
const jsonStr = '{"name":"Eve","age":22,"skills":["JS","React"]}';
const jsonObj = JSON.parse(jsonStr);
// Convert to key-value pair array
const entries = Object.entries(jsonObj);
console.log(entries);
/*
[
['name', 'Eve'],
['age', 22],
['skills', ['JS', 'React']]
]
*/
// Reverse operation: Reconstruct object from key-value pair array
const reconstructed = Object.fromEntries(entries);
console.log(reconstructed); // Original object
Application in Functional Programming
Object.entries()
integrates well with functional programming paradigms:
// Calculate the sum of an object's property values
const sumValues = obj =>
Object.entries(obj)
.map(([_, value]) => value)
.reduce((sum, val) => sum + val, 0);
const scores = { math: 90, science: 85, history: 78 };
console.log(sumValues(scores)); // 253
// Invert key-value pairs
const invert = obj =>
Object.entries(obj)
.reduce((acc, [key, value]) => {
acc[value] = key;
return acc;
}, {});
const original = { a: 1, b: 2, c: 3 };
console.log(invert(original)); // { '1': 'a', '2': 'b', '3': 'c' }
Handling Nested Objects
For nested objects, Object.entries()
can be applied recursively:
function deepEntries(obj, prefix = '') {
return Object.entries(obj).reduce((entries, [key, value]) => {
const fullKey = prefix ? `${prefix}.${key}` : key;
if (value && typeof value === 'object' && !Array.isArray(value)) {
return [...entries, ...deepEntries(value, fullKey)];
}
return [...entries, [fullKey, value]];
}, []);
}
const nested = {
user: {
name: 'Frank',
address: {
city: 'Boston',
zip: '02108'
}
},
settings: { darkMode: true }
};
console.log(deepEntries(nested));
/*
[
['user.name', 'Frank'],
['user.address.city', 'Boston'],
['user.address.zip', '02108'],
['settings.darkMode', true]
]
*/
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn