【问题标题】:Filter object properties based on array of keywords根据关键字数组过滤对象属性
【发布时间】:2020-09-03 15:28:29
【问题描述】:

寻找一种方法来仅获取“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}});

【问题讨论】:

  • 那里只有一个对象,没有数组。期望的输出是什么?
  • “我不断收到错误” ...这些错误到底是什么?他们引用的消息和线路非常有帮助

标签: javascript data-structures filter


【解决方案1】:

你的意思是这样的吗?

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%;}

【讨论】:

    猜你喜欢
    • 2018-12-25
    • 2018-07-06
    • 1970-01-01
    • 2016-05-15
    • 2021-04-15
    • 2017-03-19
    • 2018-09-27
    相关资源
    最近更新 更多