js语言:获取json中的最后一个key及value

对于一个JSON对象,可以通过以下方法获取最后一个key和value

# 1. 将JSON对象转换为数组,然后取最后一个元素

const obj = {
  "name": "John",
  "age": 20,
  "gender": "male" 
};

const lastItem = Object.entries(obj).pop();

// lastItem 是数组 ["gender", "male"]
const lastKey = lastItem[0]; 
const lastValue = lastItem[1];


# 2. 使用Object.keys()和Array.prototype.pop()

const obj = {
  "name": "John",
  "age": 20,
  "gender": "male"
};

const keys = Object.keys(obj);
const lastKey = keys.pop();
const lastValue = obj[lastKey];


# 3. 使用for...in循环遍历,记录最后一个元素


let lastKey;
let lastValue;

for (let key in obj) {
  lastKey = key;
  lastValue = obj[key]; 
}


猜你喜欢

转载自blog.csdn.net/bulucc/article/details/132052533
今日推荐