【问题标题】:How to filter and map array of objects in JavaScript?如何在 JavaScript 中过滤和映射对象数组?
【发布时间】:2019-03-03 01:50:16
【问题描述】:

我有一个对象数组,
我想从中有条件地创建另一个对象数组。

例如。 -

var devs = [
    {
        name: 'A',
        age: 26,
        tech: ['JavaScript','React'],
        addr:{
            country:'India',
            city:'Pune'
        }
    },
    {
        name: 'B',
        age: 25,
        tech: ['Node','AngularJs'],
        addr:{
            country:'USA',
            city:'NY'
        }
    },
    {
        name: 'C',
        age: 27,
        tech: ['React','AWS'],
        addr:{
            country:'UK',
            city:'London'
        }
    }
]

我想要一个对象数组,这些对象的“技术”字段数组中有 “React”
并且只想显示他们的姓名和技术,
以下是预期的输出 -

[
    {
        name: 'A',
        tech: ['JavaScript','React']
    },
    {
        name: 'C',
        tech: ['Java','React'],
    }
]

我知道可以使用条件过滤方法,
但是如何从对象数组中删除不必要的字段?
这里可以使用map方法吗?如果是,我该如何实现?

以下是我的半熟代码 -

var filteredDevs = devs.filter(temp => temp.tech.includes('React'));

【问题讨论】:

  • 重新生成你的数组
  • 正如您在标题中猜到的,是的,您应该使用map。你试过了吗?
  • 你从哪里得到'React' 来自'C'
  • @Bergi 我知道它必须使用,但不知道如何在对象数组上实现,仍在学习:D
  • @AniruddhaRaje 编写一个函数,该函数可以采用其中一个对象并返回所需形状的新对象。然后将该函数传递给map

标签: javascript arrays


【解决方案1】:

您可以使用 Array.filterArray.map 来执行此操作,使用您检查存在的 Array.includes 进行过滤tech 数组中的 React

第二步是通过仅保留原始对象的nametech 属性来映射到所需的对象。

const devs = [{"name":"A","age":26,"tech":["JavaScript","React"],"addr":{"country":"India","city":"Pune"}},{"name":"B","age":25,"tech":["Node","AngularJs"],"addr":{"country":"USA","city":"NY"}},{"name":"C","age":27,"tech":["Java","AWS"],"addr":{"country":"UK","city":"London"}}];
const devReact = devs.filter(obj => obj.tech.includes("React")).map(obj => ({"name":obj.name, "tech":obj.tech}));
console.log(devReact);

您也可以使用 Array.reduce 一次性完成,其中只累积数组中具有 React 的对象。

const devs = [{"name":"A","age":26,"tech":["JavaScript","React"],"addr":{"country":"India","city":"Pune"}},{"name":"B","age":25,"tech":["Node","AngularJs"],"addr":{"country":"USA","city":"NY"}},{"name":"C","age":27,"tech":["Java","AWS"],"addr":{"country":"UK","city":"London"}}];
const devReact = devs.reduce((acc, ele) =>  ele.tech.includes("React") ? acc.concat({"name": ele.name, "tech":ele.tech}): acc ,[]);
console.log(devReact);

【讨论】:

    【解决方案2】:

    我最好使用 Array.reduce() 来完成这个任务,只在输入数据上循环一次。

    var devs = [
        {
            name: 'A',
            age: 26,
            tech: ['JavaScript','React'],
            addr: {country:'India', city:'Pune'}
        },
        {
            name: 'B',
            age: 25,
            tech: ['Node','AngularJs'],
            addr: {country:'USA', city:'NY'}
        },
        {
            name: 'C',
            age: 27,
            tech: ['React','AWS'],
            addr: {country:'UK', city:'London'}
        }
    ];
    
    let res = devs.reduce((acc, {name, tech}) =>
    {
        tech.includes("React") && acc.push({name, tech});
        return acc;
    }, []);
    
    console.log(res);
    .as-console {background-color:black !important; color:lime;}
    .as-console-wrapper {max-height:100% !important; top:0;}

    【讨论】:

    • 我觉得这个和我的一样。
    • @Ele 是的,你是对的,但当我开始制作我的时,你的答案并不存在。如果给您带来困扰,我深表歉意……
    • 是的,我想是的!
    【解决方案3】:

    您可以使用 filter + map 函数,但是该方法使用两个循环来执行您想要的操作。

    此替代方案使用函数 reduce 生成所需的输出

    var devs = [    {        name: 'A',        age: 26,        tech: ['JavaScript','React'],        addr:{            country:'India',            city:'Pune'        }    },    {        name: 'B',        age: 25,        tech: ['Node','AngularJs'],        addr:{            country:'USA',            city:'NY'        }    },    {        name: 'C',        age: 27,        tech: ['React','AWS'],        addr:{            country:'UK',            city:'London'        }    }],
        result = devs.reduce((a, {name, tech}) => {
          if (tech.includes('React')) a.push({name, tech});
          return a;
        }, []);
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

      【解决方案4】:

      您可以使用Array.prototype.map() 删除不必要的字段

      var devs = [
          {
              name: 'A',
              age: 26,
              tech: ['JavaScript','React'],
              addr:{
                  country:'India',
                  city:'Pune'
              }
          },
          {
              name: 'B',
              age: 25,
              tech: ['Node','AngularJs'],
              addr:{
                  country:'USA',
                  city:'NY'
              }
          },
          {
              name: 'C',
              age: 27,
              tech: ['Java','AWS'],
              addr:{
                  country:'UK',
                  city:'London'
              }
          }
      ]
      
      let newArr =devs.filter(temp => temp.tech.includes('React')).map(({name,tech}) => ({name,tech}));
      console.log(newArr);

      【讨论】:

        【解决方案5】:

        您可以过滤和映射想要的属性。

        var devs = [{ name: 'A', age: 26, tech: ['JavaScript', 'React'], addr: { country: 'India', city: 'Pune' } }, { name: 'B', age: 25, tech: ['Node', 'AngularJs'], addr: { country: 'USA', city: 'NY' } }, { name: 'C', age: 27, tech: ['React', 'AWS'], addr: { country: 'UK', city: 'London' } }],
            result = devs
                .filter(({ tech }) => tech.includes('React'))
                .map(({ name, tech }) => ({ name, tech }));
        
        console.log(result);
        .as-console-wrapper { max-height: 100% !important; top: 0; }

        【讨论】:

          猜你喜欢
          • 2019-09-29
          • 2022-01-02
          • 2020-12-03
          • 2022-01-25
          • 2020-11-23
          • 1970-01-01
          • 2020-06-27
          • 1970-01-01
          • 2022-07-25
          相关资源
          最近更新 更多