我如何在React中从我的json中删除重复的值

时间:2019-04-25 15:15:52

标签: json reactjs reduce

我正在用React开发一个应用程序,但是有一个问题。我已经从json中提取了值,并且重复了这些值。我只希望每个值出现一次。

我希望它只返回一次“ Padre”的每个元素:“ CRM”,“ Permisos”和“ Telefonia”。 “ Hijo”也一样。

我已经尝试将“ .concat”更改为“ .reduce”,因为我已经知道可以这样做,但是它不起作用。我已经看到了示例,但是它们都没有在“ this.state”上运行,所以我不知道该怎么做。

您能以正确的方式帮助我吗?

这是我的json文件的一部分

[
   {
      "Id":"114",
      "Padre":"CRM",
      "Hijo":"Argumentarios"
   },
   {
      "Id":"115",
      "Padre":"CRM",
      "Hijo":"Argumentarios"
   },
   {
      "Id":"116",
      "Padre":"CRM",
      "Hijo":"Argumentarios"
   },
   {
      "Id":"44",
      "Padre":"Permisos",
      "Hijo":"root"
   },
   {
      "Id":"45",
      "Padre":"Permisos",
      "Hijo":"root"
   },
   {
      "Id":"46",
      "Padre":"Permisos",
      "Hijo":"root"
   },
   {
      "Id":"47",
      "Padre":"Permisos",
      "Hijo":"root"
   },
   {
      "Id":"50",
      "Padre":"Telefonia",
      "Hijo":"Audio"
   },
   {
      "Id":"51",
      "Padre":"Telefonia",
      "Hijo":"Audio"
   },
   {
      "Id":"52",
      "Padre":"Telefonia",
      "Hijo":"Configuracion"
   },
   {
      "Id":"70",
      "Padre":"Telefonia",
      "Hijo":"Rutas"
   }
]

出于机密原因,我无法显示实际文件。 在我的下一个代码中,我更改了对假json网址的获取

我使用@Avanthika和@blaz代码编辑我的代码。当前该代码有效,但仅显示找到的“父亲”和“儿子”的第一个值。我只需要显示一次``父亲''和``儿子''的每个不同值。结果示例: 父亲:      客户关系管理      PERMISOS 儿子:      自变量      根

目前,使用我的新代码,我只能看到:CRM(Padre)和Argumentarios(Son)。其余元素未显示。

import React, { Component } from 'react';

class Nav extends Component{
    constructor(props){
        super(props)
        this.state = {
            menuSubmenu:[]
        }
    }

    componentWillMount(){
        fetch('http://FAKE.php')
        .then(response => response.json())
        .then(menuSubmenu =>{

            menuSubmenu.forEach(datos => {
                let data = {
                    menu:datos.Padre,
                    submenu:datos.Hijo,
                    id:datos.Id
                }

                //console.log( data )
                //console.log (data.menu);
                this.setState({ 
                    menuSubmenu:this.state.menuSubmenu.concat([data])
                }) 
            })
        })
    }
    render() {
        const array = [...this.state.menuSubmenu];
        const distinctValues = array.filter(
            ({ Padre, Hijo }, index) => {
              return array.findIndex(item => item.Padre === Padre && item.Hijo === Hijo) === index;
          });
          //console.log(this.state.menuSubmenu);
          //console.log(distinctValues);

        if (distinctValues.length > 0) {
          return(
            <div>
              {distinctValues.map(datos => <Navegacion key={datos.id} menu={datos.menu} submenu={datos.submenu} />)}
            </div>
          );
        }
        return (<p>Cargando usuarios...</p>);
      }
}

class Navegacion extends Component{
    render(){
        return (
                     <ul className="list">
                        <li className="list__item">{this.props.menu}
                            <ul className="list">
                                <li className="list__item">
                                    <a href="#">{this.props.submenu}</a>
                                </li>
                            </ul>
                        </li>
                    </ul>
        )
    }
}

export default Nav;

此图片是我的json的结果。My json result

希望您可以通过“减少”功能来帮助我。 ¡非常感谢!

3 个答案:

答案 0 :(得分:1)

嗨,您可以使用lodash和uniqBy函数https://lodash.com/docs#uniqBy

_.uniqBy(menuSubmenu, function (e) {
  return e.Padre;
}); 

答案 1 :(得分:1)

  1. 您可以使用新的Set来使Padre和Hijo唯一化阵列列表。

const array = [{"Id":"114","Padre":"CRM","Hijo":"Argumentarios"},
{"Id":"115","Padre":"CRM","Hijo":"Argumentarios"},
{"Id":"116","Padre":"CRM","Hijo":"Argumentarios"},
{"Id":"44","Padre":"Permisos","Hijo":"root"},
{"Id":"45","Padre":"Permisos","Hijo":"root"},
{"Id":"46","Padre":"Permisos","Hijo":"root"},
{"Id":"47","Padre":"Permisos","Hijo":"root"},
{"Id":"50","Padre":"Telefonia","Hijo":"Audio"},
{"Id":"51","Padre":"Telefonia","Hijo":"Audio"},
{"Id":"52","Padre":"Telefonia","Hijo":"Configuracion"},
{"Id":"70","Padre":"Telefonia","Hijo":"Rutas"}];

const distinctValues = Array.from(new Set(array.map(elem => `${elem.Padre}-${elem.Hijo}`))).map(distinctVal => {
  const [ Padre, Hijo ] = distinctVal.split("-");
  return ({
    Id: array.find(elem => elem.Padre === Padre && elem.Hijo === Hijo).Id,
    Padre,
    Hijo
  });
});
console.log(distinctValues);

  1. 或者您也可以按照上述方式去lodash提取uniq值。您必须使用uniqBy。

const array = [{"Id":"114","Padre":"CRM","Hijo":"Argumentarios"},
    {"Id":"115","Padre":"CRM","Hijo":"Argumentarios"},
    {"Id":"116","Padre":"CRM","Hijo":"Argumentarios"},
    {"Id":"44","Padre":"Permisos","Hijo":"root"},
    {"Id":"45","Padre":"Permisos","Hijo":"root"},
    {"Id":"46","Padre":"Permisos","Hijo":"root"},
    {"Id":"47","Padre":"Permisos","Hijo":"root"},
    {"Id":"50","Padre":"Telefonia","Hijo":"Audio"},
    {"Id":"51","Padre":"Telefonia","Hijo":"Audio"},
   {"Id":"52","Padre":"Telefonia","Hijo":"Configuracion"},
    {"Id":"70","Padre":"Telefonia","Hijo":"Rutas"}];

const distintValues = _.uniqBy(array, elem => [elem.Padre, elem.Padre].join());

console.log(distintValues);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

您需要通过以下方式解决此问题:

render() {
  const array = [...this.state.menuSubmenu];
  // Put the solution you like here.
  // const distinctValues = the solution you like
  if (distinctValues.length > 0) {
    return(
      <div>
        {distinctValues.map(datos => <Navegacion key={datos.id} menu={datos.menu} submenu={datos.submenu} />)}
      </div>
    );
  }
  return (<p>Cargando usuarios...</p>);
}

答案 2 :(得分:0)

Original solution from Avanthika不起作用,因为在您的数据中,某些项目可能具有包含破折号(“-”)的Padre值。使用永远不会出现在Padre值中的字符作为分隔符,您会很好。

我的解决方案:

使用Array.prototype.filter

const distinctValues = this.state.menuSubmenu.filter(
  ({ Padre, Hijo }, index) => {
    return this.state.menuSubmenu.findIndex(item => item.Padre === Padre && item.Hijo === Hijo) === index;
});

使用Array.prototype.reduce,它将显得更笨重:

const distinctValues = this.state.menuSubmenu.reduce(
  (array, item) => {
    if (array.findIndex(i => i.Padre === item.Padre && i.Hijo === item.Hijo) === -1) {
      array.push(item);
    }
}, []);