为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

侃侃尔雅 2022-05-14 14:59:23
如何从对象中获取特定值,这是我的示例对象和伪代码来获得我的预期结果: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"
查看完整描述

3 回答

?
呼如林

TA贡献1798条经验 获得超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);


查看完整回答
反对 回复 2022-05-14
?
LEATH

TA贡献1936条经验 获得超6个赞

希望这可以帮助 -

  • 此代码将返回包含找到的项目的数组

  • 这将比较每个项目的所有属性/键给出的值。

  • 此外,最好创建自定义(创建 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")) 


查看完整回答
反对 回复 2022-05-14
?
绝地无双

TA贡献1946条经验 获得超4个赞

你可以使用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);


查看完整回答
反对 回复 2022-05-14
  • 3 回答
  • 0 关注
  • 176 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信