如何在ES6中使用其值过滤对象 [英] How to filter an object with its values in ES6

查看:164
本文介绍了如何在ES6中使用其值过滤对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ES6中以这种方式过滤对象的最佳方法是什么?

What is the best way to filter an object this way in ES6?

开始数据:

const acceptedValues = ["value1","value3"]
const myObject = {
    prop1:"value1",
    prop2:"value2",
    prop3:"value3"
}

预期输出:

filteredObject = {
    prop1:"value1",
    prop3:"value3"
}

推荐答案

您可以使用reduce()创建新对象,并使用includes()检查数组中是否存在对象的值.

You can use reduce() to create new object and includes() to check if value of object exists in array.

const acceptedValues = ["value1", "value3"]
const myObject = {
  prop1: "value1",
  prop2: "value2",
  prop3: "value3"
}

var filteredObject = Object.keys(myObject).reduce(function(r, e) {
  if (acceptedValues.includes(myObject[e])) r[e] = myObject[e]
  return r;
}, {})

console.log(filteredObject)

这篇关于如何在ES6中使用其值过滤对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆