[英]Function is getting called multiple times
我有一個對象數組
const data = [{
Description: "confirm"
Id: "1"
Name: "confirm"
Value: "VIP:confirm"
}, {
Description: "validate"
Id: "2"
Name: "validate"
Value: "VIP:validate"
}, {
Description: "Sent"
Id: "2"
Name: "Sent"
Value: "VIP:Sent"
}]
現在,我試圖通過傳遞值來獲取描述:
const valuesObject = [
"VIP:Confirmed",
"VIP:Validated",
"VIP:Sent"
]
現在,價值觀數據就像
const getDescription = (
value: string,
Values: Array < >
) => {
let allValues = _.find(Values, item => item.Value === value)
return resolve(allValues)
}
const resolve = (object) => {
return object?.Description ? object.Description : object?.Name ?? ''
}
現在,我在這里做,
const status = valuesObject.map((value) => {
return getDescription(value, data)
})
return status.join('/')
我期待它應該返回我確認/驗證/發送
它返回但 function 被多次調用。 誰能幫我這個?
使用_.intersectionWith()
獲取具有與值數組之一匹配的Value
屬性的對象。 然后 map 得到Description
或Name
:
const getDescription = (arr, values) => _.map( _.intersectionWith(arr, values, (o, v) => o.Value === v), // get all objects with matching values ({ Description, Name = '' }) => Description || Name // map to description / name / empty string ).join('/') const data = [{"Description":"Confirmed","Id":"1","Name":"confirm","Value":"VIP:Confirmed"},{"Description":"Validated","Id":"2","Name":"validate","Value":"VIP:Validated"},{"Description":"Sent","Id":"2","Name":"Sent","Value":"VIP:Sent"}] const valuesObject = ["VIP:Confirmed","VIP:Validated","VIP:Sent"] const result = getDescription(data, valuesObject) console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.19/lodash.js"></script>
使用 lodash/fp 您可以使用_.flow()
() 生成getDescription()
function :
const getDescription = _.flow( _.intersectionWith((o, v) => o.Value === v), // get all objects with matching values _.map(({ Description, Name = '' }) => Description || Name), // map to description / name / empty string _.join('/') ) const data = [{"Description":"Confirmed","Id":"1","Name":"confirm","Value":"VIP:Confirmed"},{"Description":"Validated","Id":"2","Name":"validate","Value":"VIP:Validated"},{"Description":"Sent","Id":"2","Name":"Sent","Value":"VIP:Sent"}] const valuesObject = ["VIP:Confirmed","VIP:Validated","VIP:Sent"] const result = getDescription(data, valuesObject) console.log(result)
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.