简体   繁体   English

返回数组中的对象属性

[英]return object property in array

I have an array that looks like this:我有一个看起来像这样的数组:

const arr = [{
    name: 'One',
    id: 1
  },
  {
    name: 'Two',
    id: 2
  }
];

I then want to return just the name of the object if the id matches.然后,如果 id 匹配,我只想返回对象的名称。

I have tried something like the following, but it returns the whole object in an array:我尝试过类似以下的操作,但它以数组形式返回整个对象:

 const arr = [{ name: 'One', id: 1 }, { name: 'Two', id: 2 } ]; const getNameFromId = id => { return arr.filter(item => { if (item.id === id) { return item.name; } }) } const res = getNameFromId(1) // This should return `'One'` console.log(res)

You may prefer to use find instead.您可能更喜欢使用find代替。

const id = 2
arr.find(val => val.id === id).name

you should check if find return a value or not你应该检查find返回一个值

const getNameFromId = id => {
  const search = arr.find(val => val.id === id)
  if (search) {
    return search.name
  }
}

If you use filter (which returns an array) you can grab the name from the first element.如果您使用filter (它返回一个数组),您可以从第一个元素中获取name find as mentioned in the other answer might better suit your needs, however. find ,在另一个答案中提到的find可能更适合您的需求。

 const arr = [{ name: 'One', id: 1 }, { name: 'Two', id: 2} ]; const getNameFromId = (id) => { return arr.filter(item => item.id === id)[0].name; } const res = getNameFromId(1) console.log(res)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM