如何在ReactJS中搜索数组内部

时间:2019-06-18 12:10:26

标签: arrays reactjs

我想在数组中搜索以找到东西

这是我在this.state中的数组

materialUnits: [
                    {
                        unitID: '',
                        barcodeNo: '',
                        salePrice: '',
                        vatValue: '',
                        isdefault: '',
                        rate: ''
                    }
                ]

然后在出现类似情况的情况下

const value = "1";
const searcharray = this.state.materialUnits.filter(data => {
  return data.isdefault === value;
});

if (searcharray.length === 0) {
  //do something
} else {
  alert("cant 2 defaults");
}

4 个答案:

答案 0 :(得分:3)

return materialUnits.find(item => item.isdefault !== 1);

答案 1 :(得分:2)

return !materialUnits.filter(item => item.isdefault == 1).length > 0;

答案 2 :(得分:1)

var materialUnits =  [
	{
		unitID: '1',
		barcodeNo: '1',
		salePrice: '1',
		vatValue: '1',
		isdefault: '1',
		rate: '1'
	},
	{
		unitID: '2',
		barcodeNo: '2',
		salePrice: '2',
		vatValue: '2',
		isdefault: '2',
		rate: '2'
	}
];

function filterData(data){
  return data.isdefault === '1' ? false: true;
}

console.log(materialUnits.filter(filterData));

答案 3 :(得分:1)

function Test (){
    const [materialUnits,setmaterialUnits] = React.useState([
      {
          unitID: '',
          barcodeNo: '',
          salePrice: '',
          vatValue: '',
          isdefault: '1',
          rate: ''
      },
                 {
          unitID: '',
          barcodeNo: '',
          salePrice: '',
          vatValue: '',
          isdefault: '2',
          rate: ''
      },
  ]);
  const [arrayfilter,setfiltearray] =  React.useState(materialUnits);
  
  // call function on input change to filter the array
 
  function filterarray(value){
if(value!==""){
  var newarray =  materialUnits.filter(data=>{return(data.isdefault === value)});
  console.log(newarray)
  setfiltearray(newarray)
}
else{
  setfiltearray(materialUnits)
}

  }

//conditional render depending on  array filtration

  function renderUnit(){
    if(arrayfilter.length===0){
      return(<div>Not found</div>)
    }
    else{
      var units = arrayfilter.map((data,key)=>{return(<div key={key}>{data.isdefault}</div>)})
      return units;
    }
  }
  return(
    <div>
<input type ="text" onChange={e=>filterarray(e.target.value)}/>
{renderUnit()}
</div>
  )
  }