React中如何从{"B8":"C6"}格式的对象中获取键值对?
Hey there! Let's sort out this issue you're facing. First off, the reason move[1] returns undefined is because {"G8":"F6"} is a JavaScript object, not an array. Arrays use numeric indices like [0] or [1] to access items, but objects rely on named keys to retrieve values—so numeric indices don't work here.
Since your object only has one key-value pair, here are a few straightforward ways to get from and to correctly:
Method 1: Destructure with Object.entries()
This is my favorite approach—it's clean and concise:
const [from, to] = Object.entries(move)[0];
Object.entries(move)converts your object into an array of key-value pairs:[["G8", "F6"]]- We grab the first (and only) entry with
[0], then use array destructuring to assign the key tofromand the value totoin one line.
Method 2: Use Object.keys() and Object.values()
If you prefer to fetch the key and value separately, this works just as well:
const from = Object.keys(move)[0]; // Gets "G8" const to = Object.values(move)[0]; // Gets "F6"
Object.keys(move)returns an array of all the object's keys:["G8"]Object.values(move)returns an array of all the object's values:["F6"]- We take the first element from each array since there's only one entry in your object.
Method 3: Loop with for...in (for older browser support)
If you need to support older environments where Object.entries/keys/values aren't available, a simple loop does the trick:
let from, to; for (const key in move) { // Ensure we're only accessing the object's own properties (not inherited ones) if (move.hasOwnProperty(key)) { from = key; to = move[key]; break; // Exit the loop right away since we only have one pair } }
Any of these methods will correctly assign from = "G8" and to = "F6" from your move object.
内容的提问来源于stack exchange,提问作者benpalmer

