访问 json 的内部对象
Getting access to the inner object of a json
我正在为我的 React 项目使用 Ant Design 框架。我想访问内部对象“quote.USD.price”并将其放在数据源数组中,但不幸的是,我不知道如何操作。
据我了解,您正在寻找类似的东西。您可以通过以下任何方法访问对象的内部字段
const crypto = {
quote: {
USD: {
price: 10
}
}
}
const data1 = {
title: "price",
dataIndex: crypto.quote.USD.price,
key: "id"
}
const data2 = {
title: "price",
dataIndex: crypto["quote"]["USD"]["price"],
key: "id"
}
console.log(data1)
console.log(data2)
//both should output the same
我认为您想解析一个字符串,该字符串与表示值在某些嵌套对象中的位置的点连接。
我写了一个实用函数来递归地做这件事。您可以在 this React project 中看到它的实际效果。我是用 TypeScript 做的,但你可以删除类型注释。
const findPriceByMultipleKeys = (dataKey: string, data: any): string | number => {
let keys: string[] = dataKey.split(".");
// If dataKey is one key without any dot notation, return the value
if(keys.length === 1) return data[dataKey];
let key: string = "";
let keysRest: string[] = [];
if (keys.length) {
// get first element from keys
// capture the rest of the keys
[key, ...keysRest] = keys;
}
// Check if there any more indexes left to evaluate
if (keysRest.length) {
// Transform keysRest to string concatenated with dots
let keysRestStr = keysRest.join(".");
// Let the function call itself to go deeper in the object with
// the remaining indexes and objects
return findPriceByMultipleKeys(keysRestStr, data[key]);
} else {
// If no keys left to evaluate, return the value
return data[key];
}
};
我正在为我的 React 项目使用 Ant Design 框架。我想访问内部对象“quote.USD.price”并将其放在数据源数组中,但不幸的是,我不知道如何操作。
据我了解,您正在寻找类似的东西。您可以通过以下任何方法访问对象的内部字段
const crypto = {
quote: {
USD: {
price: 10
}
}
}
const data1 = {
title: "price",
dataIndex: crypto.quote.USD.price,
key: "id"
}
const data2 = {
title: "price",
dataIndex: crypto["quote"]["USD"]["price"],
key: "id"
}
console.log(data1)
console.log(data2)
//both should output the same
我认为您想解析一个字符串,该字符串与表示值在某些嵌套对象中的位置的点连接。
我写了一个实用函数来递归地做这件事。您可以在 this React project 中看到它的实际效果。我是用 TypeScript 做的,但你可以删除类型注释。
const findPriceByMultipleKeys = (dataKey: string, data: any): string | number => {
let keys: string[] = dataKey.split(".");
// If dataKey is one key without any dot notation, return the value
if(keys.length === 1) return data[dataKey];
let key: string = "";
let keysRest: string[] = [];
if (keys.length) {
// get first element from keys
// capture the rest of the keys
[key, ...keysRest] = keys;
}
// Check if there any more indexes left to evaluate
if (keysRest.length) {
// Transform keysRest to string concatenated with dots
let keysRestStr = keysRest.join(".");
// Let the function call itself to go deeper in the object with
// the remaining indexes and objects
return findPriceByMultipleKeys(keysRestStr, data[key]);
} else {
// If no keys left to evaluate, return the value
return data[key];
}
};