从对象中提取名称与测试匹配的属性
From an object, extract properties with names matching a test
我有一个 props 对象,它将包含一组未知的属性,我想根据它们的前缀提取其中的一些属性。我有一些有用的东西(太棒了!),但它看起来很啰嗦,我想知道是否有更惯用的方法来做到这一点?
const props = {
bingo: 1,
bongo: 2,
mingo: 3,
bango: 4
}
const bFields = {}
Object.keys(props).filter(k => (k.startsWith('b'))).forEach(k => (
bFields[k] = props[k]
))
console.log(props)
console.log(bFields)
How about this one-liner
let props = {bingo:1,bongo:2,mingo:3,bango:4}, filteredProps = {};
Object.keys(props).forEach(x => x.startsWith('b') ? filteredProps[x] = props[x] : '');
console.log(filteredProps);
你也可以使用reduce:
const props = {
bingo: 1,
bongo: 2,
mingo: 3,
bango: 4
}
const bFields = Object.keys(props).reduce((acc, prop) => {
if (prop.startsWith('b')) {
acc[prop] = props[prop]
}
return acc
}, {})
console.log(props);
console.log(bFields);
我这样做是为了达到目标 "More understandable by someone that doesn't code" 我不知道是不是这样,但这是代码。
const props = {
bingo: 1,
bongo: 2,
mingo: 3,
bango: 4
}
const bFields = {};
function matchByStart (key, idx, all) {
if (key.toLowerCase().startsWith("b")) bFields[key] = props[key];
}
Object.keys(props).map(matchByStart);
console.log(bFields);
希望对您有所帮助!
edit: Also I put the method toLowerCase()!
您也可以使用Object.fromEntries
、Object.entries
const props = {"bingo":1,"bongo":2,"mingo":3,"bango":4}
const bFields = Object.fromEntries(Object.entries(props).filter(([k])=>k.toLowerCase().startsWith('b')))
console.log(bFields)
我有一个 props 对象,它将包含一组未知的属性,我想根据它们的前缀提取其中的一些属性。我有一些有用的东西(太棒了!),但它看起来很啰嗦,我想知道是否有更惯用的方法来做到这一点?
const props = {
bingo: 1,
bongo: 2,
mingo: 3,
bango: 4
}
const bFields = {}
Object.keys(props).filter(k => (k.startsWith('b'))).forEach(k => (
bFields[k] = props[k]
))
console.log(props)
console.log(bFields)
How about this one-liner
let props = {bingo:1,bongo:2,mingo:3,bango:4}, filteredProps = {};
Object.keys(props).forEach(x => x.startsWith('b') ? filteredProps[x] = props[x] : '');
console.log(filteredProps);
你也可以使用reduce:
const props = {
bingo: 1,
bongo: 2,
mingo: 3,
bango: 4
}
const bFields = Object.keys(props).reduce((acc, prop) => {
if (prop.startsWith('b')) {
acc[prop] = props[prop]
}
return acc
}, {})
console.log(props);
console.log(bFields);
我这样做是为了达到目标 "More understandable by someone that doesn't code" 我不知道是不是这样,但这是代码。
const props = {
bingo: 1,
bongo: 2,
mingo: 3,
bango: 4
}
const bFields = {};
function matchByStart (key, idx, all) {
if (key.toLowerCase().startsWith("b")) bFields[key] = props[key];
}
Object.keys(props).map(matchByStart);
console.log(bFields);
希望对您有所帮助!
edit: Also I put the method toLowerCase()!
您也可以使用Object.fromEntries
、Object.entries
const props = {"bingo":1,"bongo":2,"mingo":3,"bango":4}
const bFields = Object.fromEntries(Object.entries(props).filter(([k])=>k.toLowerCase().startsWith('b')))
console.log(bFields)