我必須按值在物件陣列中找到一個屬性,它是一個字串串列。
例如我有這樣的東西:
const colors ={
colors-1: [{color: 'blue'}],
colors-2: [{color: 'gray'}, {color: 'red'}],
colors-3: [{color: 'white'}]
}
我想colors-2通過陣列值內的字串獲取例如屬性。
像這樣的東西:
findPropertyByValue(colors, 'red')
并輸出:
'colors-2'
你能告訴我如何實作這一目標嗎?謝謝。
uj5u.com熱心網友回復:
以下是您如何實作您想要的目標。請注意,我在引號中添加了您的物件鍵,因為它們包含-,它不會以其他方式作業。
const colors = {
"colors-1": [{ color: "blue" }],
"colors-2": [{ color: "gray" }, { color: "red" }],
"colors-3": [{ color: "white" }]
};
function findPropertyByValue(colors, value) {
for (let color in colors) {
if (colors[color].some((c) => c.color == value)) {
return color;
}
}
return ""; // if there isn't one
}
console.log(findPropertyByValue(colors, "red"));
uj5u.com熱心網友回復:
這是使用findand的解決方案some。
它獲取colors物件的條目并找到具有輸入顏色元素的條目。
查找回傳一個條目,[key,value]以便獲取第 0 個元素的鍵
在這里,我假設單一顏色具有唯一鍵。
添加了?.之前[0](可選鏈接 - 僅在可用時訪問),以便在輸入未找到的顏色時不會出現錯誤(回傳undefined)。||如果查找步驟回傳,運算子用于回傳類似“未找到”的訊息undefined
const colors ={
'colors-1': [{color: 'blue'}],
'colors-2': [{color: 'gray'}, {color: 'red'}],
'colors-3': [{color: 'white'}]
}
const findPropertyByValue = (obj,col) => Object.entries(obj).find(([k,v])=>v.some(({color}) => color===col))?.[0] || 'not found'
console.log(findPropertyByValue(colors,'white'))
console.log(findPropertyByValue(colors,'gray'))
console.log(findPropertyByValue(colors,'red'))
console.log(findPropertyByValue(colors,'blue'))
console.log(findPropertyByValue(colors,'green'))
uj5u.com熱心網友回復:
以下可能是實作預期目標的一種可能解決方案:
代碼片段
const findPropertyByValue = (haystack, needle) => (
Object.keys(haystack)
.find(
k => (haystack[k]).some(
({color}) => color === needle
)
) || 'not found'
);
const colors ={
"colors-1": [{color: 'blue'}],
"colors-2": [{color: 'gray'}, {color: 'red'}],
"colors-3": [{color: 'white'}]
};
console.log('find red: ', findPropertyByValue(colors, 'red'));
console.log('find cyan: ', findPropertyByValue(colors, 'cyan'));
解釋
- 遍歷物件的 (
haystack) 鍵 .find在 value 陣列中,colorprop 匹配的元素needle(正在搜索的顏色)- 如果找到任何這樣的匹配項,則回傳密鑰
- 否則,回傳
not found
uj5u.com熱心網友回復:
你可以試試這個:
const colors = {
"colors-1": [{ color: "blue" }],
"colors-2": [{ color: "gray" }, { color: "red" }],
"colors-3": [{ color: "white" }],
};
function findPropertyByValue(obj, colorName) {
return Object.entries(obj).find((entry) =>
entry[1].some((color) => color.color === colorName)
)?.[0];
}
console.log(findPropertyByValue(colors, "red"));
console.log(findPropertyByValue(colors, "not in list"));
此解決方案將回傳具有指定顏色的所有欄位:
const colors = {
"colors-1": [{ color: "blue" }],
"colors-2": [{ color: "gray" }, { color: "red" }],
"colors-3": [{ color: "white" }],
"colors-4": [{ color: "white" }, { color: "red" }],
};
function findPropertyByValue(obj, colorName) {
return Object.entries(obj).reduce(
(acc, entry) =>
entry[1].some((color) => color.color === colorName)
? [...acc, entry[0]]
: acc,
[]
);
}
console.log(findPropertyByValue(colors, "red"));
console.log(findPropertyByValue(colors, "not in list"));
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/450038.html
標籤:javascript
