这是我的数组的样子:
const items = [
{ uuid: '123-1234-567', amountMoney: '20,02' },
{ uuid: '111-111-111', amountMoney: '44.04' }
]
而且我在变量中有uuid键:
const uuid = '111-111-111';
现在基于此uuid,我想从amountMoney:44.04
中提取值。
您如何在js中以一种不错的方式编写此代码?
您可以使用Array.prototype.find:
items.find(item => item.uuid === uuid) // -> found object
const items = [
{ uuid: '123-1234-567', amountMoney: '20,02' },
{ uuid: '111-111-111', amountMoney: '44.04' }
]
const uuid = '111-111-111';
const foundItem = items.find(item => item.uuid === uuid);
if (foundItem) {
console.log(foundItem.amountMoney)
}