[英]How to return a property of an object if its other property is known?
I have array of objects with unique names: 我有具有唯一名称的对象数组:
let arr = [
{
'name':'B',
'id': 1
},
{
'name': 'c',
'id': 12
},
{
'name': 'a',
'id': 13
}
]
How can I get id
if I know the name
. 如果我知道
name
怎么获得id
。 For example I have B
and it need to return 1
? 例如我有
B
,它需要返回1
?
My solution : 我的解决方案:
const foo = (arr, name) => arr.filter(el => el.name === name)[0].id
foo(arr, 'B') // 1
Hope there is a better solution to this problem 希望有一个更好的解决方案
You should use Array.prototype.find()
instead of Array.prototype.filter()
, because .find()
returns only the first matching element of the array - .filter()
returns all matching elements. 您应该使用
Array.prototype.find()
而不是Array.prototype.filter()
,因为.find()
仅返回数组的第一个匹配元素.filter()
返回所有匹配的元素。 Your code should look like this: 您的代码应如下所示:
const foo = (arr, name) => arr.find(el => el.name == name).id;
Working snippet: 工作片段:
let arr = [ { 'name': 'B', 'id': 1 }, { 'name': 'c', 'id': 12 }, { 'name': 'a', 'id': 13 } ] const foo = (arr, name) => arr.find(el => el.name == name).id; var theID = foo(arr, 'B'); console.log(theID);
Array.prototype.find
is fine for few lookups if you don't mind that it's not supported in IE, and that it can result in error if the item is not found. 如果您不介意IE中不支持
Array.prototype.find
则可以进行少量查找,如果找不到该项,则可能导致错误。 For multiple lookups, I recommend making a lookup object : 对于多次查找,我建议制作一个查找对象:
const arr = [ { name:'B', id: 1 }, { name: 'c', id: 12 }, { name: 'a', id: 13 } ] const obj = arr.reduce((o, v) => (o[v.name] = v.id, o), {}) console.log( obj['B'] ) // 1 console.log( obj['A'] ) // undefined
If by any chance the data is from JSON.parse
: 如果任何数据来自
JSON.parse
:
const obj = {}, json = '[{"name":"B","id":1},{"name":"c","id":12},{"name":"a","id":13}]' JSON.parse(json, (k, v) => v.name ? (obj[v.name] = v.id) : v) console.log( obj['B'] ) // 1 console.log( obj['A'] ) // undefined
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.