我需要使用字串陣列中定義的路徑從記錄中提取一個值。我想出了以下解決方案。它有效,但在我看來,這段代碼似乎有點太復雜而難以理解。我想知道是否有更好的方法來檢查值是否是原始型別,以及是否有人可以以更簡單的方式思考來完成這項作業。
const record = {
firstName: "Joe Doe",
personalData: {
email: "[email protected]"
}
};
const path = ["personalData","email"];
const getJsonValueUsingPath = (record, path, index) => {
const isPrimitiveType =
Object(record[path[index]]) !== record[path[index]];
if (isPrimitiveType) {
return record[path[index]];
} else {
return getColumnValue(record[path[index]], path, index 1);
}
};
我需要此功能,因為我使用的是需要此類功能的第三方庫。請不要說使用字串陣列提取物件屬性值是個壞主意。
uj5u.com熱心網友回復:
不確定這是否是您所追求的。這只是對您所擁有的內容的一點更新,但它提供了一種檢測原語的替代方法
const record = {
firstName: "Joe Doe",
personalData: {
email: "[email protected]"
}
};
const path = ["firstName", "personalData", "email"];
let primitives = ['string', 'number', 'bigint', 'boolean', 'undefined', 'symbol', 'null'];
const getJsonValueUsingPath = (rec, pa, index) => {
let item = rec[pa[index]];
//console.log(typeof item)
return primitives.includes((typeof item).toLowerCase()) ? item : getJsonValueUsingPath(item, path, index 1)
}
console.log(getJsonValueUsingPath(record, path, 0));
console.log(getJsonValueUsingPath(record, path, 1));
uj5u.com熱心網友回復:
為簡化起見,您可以洗掉原始檢查并假設路徑正確并導致需要回傳的值,無論它是否原始。
其次,您可以用reduce()整個路徑上的呼叫替換回圈,路徑中的最后一項除外。
const getValueUsingPath = (record, path) => {
path = [...path]; // avoid mutating original path (optional)
const last = path.pop();
return path.reduce((record, item) => record[item], record)[last];
};
const record = {
firstName: "Joe Doe",
personalData: {
email: "[email protected]"
}
};
const path = ["personalData","email"];
console.log(getValueUsingPath(record, path));
uj5u.com熱心網友回復:
lodash如果你不介意的話:
const _ = require('lodash');
const record = { firstName: "Joe Doe", personalData: { email: "[email protected]" } };
const path = ["personalData","email"];
_.get(record, path); // '[email protected]'
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/381104.html
標籤:javascript 数组 算法
