js 过滤掉一个对象的值为空的键值对,但不过滤掉值为0的键值对
时间: 2023-02-08 09:30:25 浏览: 127
可以使用 `Object.entries()` 和 `Array.filter()` 方法来过滤掉对象中值为空的键值对。
例如:
```js
let obj = {a: 1, b: "", c: 0, d: null};
let filteredObj = Object.fromEntries(
Object.entries(obj).filter(([key, value]) => value !== "" && value !== null)
);
console.log(filteredObj)
// 输出: {a: 1, c: 0}
```
上面的代码使用`Object.entries()`获取对象的键值对数组,然后使用 `Array.filter()` 方法过滤掉值为空的键值对,最后使用 `Object.fromEntries()` 将数组重新转成对象。
相关问题
js按照数组中每个对象的某一个键值值为字符串排序并去重
可以使用`Array.prototype.sort()`和`Array.prototype.filter()`方法来实现按照数组中每个对象的某一个键值字符串排序并去重的操作。
下面是一个示例代码:
```js
const arr = [
{ name: 'John', age: 30 },
{ name: 'Mary', age: 25 },
{ name: 'Lucy', age: 28 },
{ name: 'John', age: 35 },
{ name: 'Lucy', age: 27 }
];
const key = 'name'; // 按照 name 字段排序
const sortedArr = arr.sort((a, b) => {
if (a[key] < b[key]) {
return -1;
} else if (a[key] > b[key]) {
return 1;
} else {
return 0;
}
});
const uniqueArr = sortedArr.filter((item, index, arr) => {
return index === 0 || item[key] !== arr[index - 1][key];
});
console.log(uniqueArr);
// 输出:[
// { name: 'John', age: 30 },
// { name: 'Lucy', age: 28 },
// { name: 'Mary', age: 25 }
// ]
```
上面的代码中,首先使用`Array.prototype.sort()`方法按照指定的键值进行排序,然后使用`Array.prototype.filter()`方法过滤掉重复的项,最后得到一个按照指定键值排序并去重的新数组。
filter过滤对象键值
对于这个问题,根据提供的引用内容,filter过滤对象键值的实现方法是通过在Vue中使用filter函数来创建一个过滤器。在代码中,我们可以使用Vue.filter函数来定义一个名为parseStr的过滤器。这个过滤器可以接收两个参数,一个是字符串(str),一个是对象(obj)。在函数中,我们可以通过访问filterData对象来获取过滤器需要的数据,并返回相应的键值。
以下是一个示例代码,展示了如何在Vue中创建filter过滤对象键值的过程:
1. 首先,在项目中导入filterData.js文件和Vue:
import filterData from './filterData.js';
import Vue from 'vue';
2. 然后,使用Vue.filter函数来创建一个名为parseStr的过滤器:
Vue.filter('parseStr', (str, obj) => {
return filterData[obj.kind]['com'][str];
});
这样,我们就成功创建了一个名为parseStr的过滤器,它可以根据传入的参数str和obj来获取filterData中对应的键值,并返回结果。
希望这个回答对你有所帮助!如果还有其他问题,请随时提问。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)