在对象中查找特定名称中的值

如何从对象中获取特定值,这是我的示例对象和伪代码来获得我的预期结果:


items = [

    {code: "1", fruits: "APPLE", color: "red"},

    {code: "2", fruits: "BANANA", color: "dummy"},

    {code: "3", fruits: "BANANA", color: "anotherDummy"},

    {code: "4", fruits: "ORANGE", color: "orange"}

]



items.find("BANANA")

我应该循环它还是有一个可以轻松找到值的函数。

预期结果:


2,"BANANA","yellow"

3,"BANANA","anotherDummy"


侃侃尔雅
浏览 177回答 3
3回答

呼如林

你可以你filter的数组const items = [  {code: "1", fruits: "APPLE", color: "red"},  {code: "2", fruits: "BANANA", color: "dummy"},  {code: "3", fruits: "BANANA", color: "anotherDummy"},  {code: "4", fruits: "ORANGE", color: "orange"}];const keyword = 'BANANA';const filter = items.filter(item => (item.code === keyword || item.fruits === keyword ||item.color === keyword));console.log(filter);也适用于多个过滤器/搜索const items = [  {code: "1", fruits: "APPLE", color: "red"},  {code: "2", fruits: "BANANA", color: "dummy"},  {code: "3", fruits: "BANANA", color: "anotherDummy"},  {code: "4", fruits: "ORANGE", color: "orange"}];const keyword = ['APPLE', 'BANANA'];const filter = items.filter(item => (  keyword.includes(item.code)  || keyword.includes(item.fruits)  || keyword.includes(item.color)));console.log(filter);

LEATH

希望这可以帮助 -此代码将返回包含找到的项目的数组这将比较每个项目的所有属性/键给出的值。此外,最好创建自定义(创建 findCustom() 函数)而不是覆盖内置的 find() 方法。   var items = [{code: "1", fruits: "APPLE", color: "red"},    {code: "2", fruits: "BANANA", color: "dummy"},    {code: "3", fruits: "BANANA", color: "anotherDummy"},    {code: "4", fruits: "ORANGE", color: "orange"}]        items.findCustom = (value) =>{      let results = [];      items.find((item) => {      var listKeys = Object.keys(item);      listKeys.forEach((keyName) => {        if(item[keyName] == value)           results.push(item);            })    })    return results;    }    console.log(items.findCustom("BANANA")) 

绝地无双

你可以使用filter方法let filteredArray = items.filter(item => item.fruits ==='BANANA');console.log(filteredArray);更新对于更多动态过滤器,您可以创建要查找的字符串列表让我们说:let fruitsToFilter = ['BANANA', 'APPLE',...]然后就可以使用像这样的过滤方法来实现动态过滤let filteredArray = items.filter(item => fruitsToFilter.includes(item.fruits));console.log(filteredArray);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript