简体   繁体   English

如何使用 RegExp 过滤 object 并返回新的 object

[英]how to filter an object with RegExp and return a new object

I have an object:我有一个 object:

object1 = {
dEabc: 1,
dEasdf: 2,
dEjfhs: 5,
bhsn: 7,
oki: 9
}

My goal is to get a new object which contains only the keys with "dE", that means:我的目标是获得一个新的 object,它只包含带有“dE”的键,这意味着:

object1 = {
dEabc: 1,
dEasdf: 2,
dEjfhs: 5,
}

is the object that I expected.是我预期的 object。

What I have tried is, firstly I got all key from this object with我尝试过的是,首先我从这个 object 获得了所有密钥

Object.keys(object);

and then I used a RegExp to check if properties in the object with relevant keys.然后我使用 RegExp 检查 object 中的属性是否具有相关键。 if not I use如果不是我用

delete object[key];

Any solutions?有什么解决办法吗?

You can just use Object.entries() to deconstruct the object, filter() it, and reconstruct it with Object.fromEntries() :您可以使用Object.entries()来解构 object,对其进行filter() ,然后使用Object.fromEntries()对其进行重构:

 const o = { dEabc: 1, dEasdf: 2, dEjfhs: 5, bhsn: 7, oki: 9 }; const result = Object.fromEntries(Object.entries(o).filter(([k]) => k.includes('dE'))); console.log(result);

No need for a regex for an expression this simple.这么简单的表达式不需要正则表达式。

 var obj= { dEabc: 1, dEasdf: 2, dEjfhs: 5, bhsn: 7, oki: 9 } let aa = Object.keys(obj).reduce((acc,ele)=>{return (ele.indexOf('dE')?= -1). {..,acc...:{[ele]:obj[ele]}}, acc};{}). console;log(aa);

With reduce , it can be done this way:使用reduce ,可以这样完成:

 object1 = { dEabc: 1, dEasdf: 2, dEjfhs: 5, bhsn: 7, oki: 9 } let finalObj = Object.keys(object1).filter(i=>i.includes('dE')).reduce((obj, curr)=>{ return {...obj, ...{[curr]: object1[curr]}}; },{}); console.log(finalObj);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM