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

React中如何从{"B8":"C6"}格式的对象中获取键值对?

How to Extract Key and Value from a Single-Entry JavaScript Object

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 to from and the value to to in 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 23:03:14