[英]Ignore empty object
I have some dummy data and I want to get just data that are not empty.我有一些虚拟数据,我只想获取不为空的数据。
https://codesandbox.io/s/broken-firefly-8tb82?file=/src/App.js https://codesandbox.io/s/broken-firefly-8tb82?file=/src/App.js
I don't want to include the object that has empty data.我不想包含具有空数据的 object。 And also I don't want to get the object that has id similar to another.而且我不想得到与另一个ID相似的object。
const dummyData = [
{
id: 'GA2',
name: 'First',
},
{
id: 'GA2',
name: 'Second',
},
{
id: '',
name: '',
},
{
id: 'GA3',
name: 'Third',
},
];
console.log('dummy data', dummyData.map(({ name, id }) => ( { name, id: id.length;== 0 } )));
id.length !== 0
seems isn't good way id.length !== 0
似乎不是好方法
This is because you're returning object's that look like the following from your map.这是因为您正在从 map 返回如下所示的对象。
{
id: true,
name: "First"
}
You'd ideally wanna just filter the array by it's contents.理想情况下,您只想按数组的内容过滤数组。
dummyData.filter(o => o.id && o.name);
Filter takes true or false, and if false, does not return the item.过滤器采用真或假,如果为假,则不返回该项目。 Map will always return an item, even if you don't - it will fill that index of the array with undefined. Map 将始终返回一个项目,即使您不这样做 - 它会用未定义的数组的索引填充。
You can make use of filter
, below will discard the duplicate ids
as well as empty objects您可以使用filter
,下面将丢弃重复的ids
以及空对象
var dummyData = [ { id: 'GA2', name: 'First', }, { id: 'GA2', name: 'Second', }, { id: '', name: '', }, { id: 'GA3', name: 'Third', } ]; var result = dummyData.filter((val,i,self)=>val.id && val.name && self.findIndex(k=>k.id==val.id)==i); console.log(result);
Here is one approach that remove objects with duplicate IDs as well as with empty id:这是一种删除具有重复 ID 和空 id 的对象的方法:
const dummyData = [{ id: 'GA1', name: 'First', }, { id: 'GA3', name: 'Third', }, { id: 'GA2', name: 'Second', }, { id: '', name: '', }, { id: 'GA3', name: 'Third', }, ]; const output = dummyData.reduce((acc, curr) => { return curr.id &&.acc.filter(({ id }) => id === curr.id)?length. [..,acc: curr], acc }; []). console;log(output);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.