寻找一种方法来仅获取“ test”对象中包含“ asSrcElementsTypes”值之一的对象
在数组上映射以检查它们是否是这些值中的最佳方法是什么?当我尝试映射数组以查看它是否与测试对象中的键匹配时,下面的代码不断出现错误。
var asSrcElementsTypes = ['-input', '-src'];
var test = { "exitUrl":"googl.com", "otherData1":"otherData1" "F2-1_largerLegal-input": "F2-1_largerLegal-input", "F2-1_copy-font": "Ultra", "F2-3_copy-fontSize": "12", "F2-1_copy-input": "F2-1_copy-input", "F2-1_frameLegal-input": "Ultra", "F2-1_frameLegal-fontSize": "14", "F2-2_copy-input": "F2-2_copy-input", "F2-3_copy-input": "F2-3_copy-input", "F2-3_copy-font": "Medium", "F2-1_copy-fontSize": "10", "F2-1_product-src": "250/50/F2-1_product.png", "F2-2_copy-font": "Medium", "F2-2_copy-fontSize": "11", "F2-1_largerLegal-fontSize": "13"};
const allButMe = data.filter(function(value, key){ if(key.indexOf.indexOf(asSrcElementsTypes.map()) !== -1){return key}});
答案 0 :(得分:2)
你的意思是那样吗?
const asSrcElementsTypes = ['-input', '-src'],
test = { "F2-1_largerLegal-input": "F2-1_largerLegal-input", "F2-1_copy-font": "Ultra", "F2-3_copy-fontSize": "12", "F2-1_copy-input": "F2-1_copy-input", "F2-1_frameLegal-input": "Ultra", "F2-1_frameLegal-fontSize": "14", "F2-2_copy-input": "F2-2_copy-input", "F2-3_copy-input": "F2-3_copy-input", "F2-3_copy-font": "Medium", "F2-1_copy-fontSize": "10", "F2-1_product-src": "250/50/F2-1_product.png", "F2-2_copy-font": "Medium", "F2-2_copy-fontSize": "11", "F2-1_largerLegal-fontSize": "13"},
result = Object.fromEntries(
Object
.entries(test)
.filter(([key,value]) =>
asSrcElementsTypes
.some(type =>
key.includes(type)))
)
console.log(result)
.as-console-wrapper{min-height:100%;}
或者,也许是基于.reduce()
的替代方式:
const asSrcElementsTypes = ['-input', '-src'],
test = { "F2-1_largerLegal-input": "F2-1_largerLegal-input", "F2-1_copy-font": "Ultra", "F2-3_copy-fontSize": "12", "F2-1_copy-input": "F2-1_copy-input", "F2-1_frameLegal-input": "Ultra", "F2-1_frameLegal-fontSize": "14", "F2-2_copy-input": "F2-2_copy-input", "F2-3_copy-input": "F2-3_copy-input", "F2-3_copy-font": "Medium", "F2-1_copy-fontSize": "10", "F2-1_product-src": "250/50/F2-1_product.png", "F2-2_copy-font": "Medium", "F2-2_copy-fontSize": "11", "F2-1_largerLegal-fontSize": "13"},
result = Object
.keys(test)
.reduce((r,key) => (
asSrcElementsTypes.some(type =>
key.includes(type)) &&
(r[key]=test[key]), r), {})
console.log(result)
.as-console-wrapper{min-height:100%;}