javascript过滤一个对象

我有以下 Javascript 对象。


var data = 

{

  "type": [

    "car",

    "bike"

  ],

  "wheels": [

    "4",

    "2"

  ],

  "open": [

    "Jan",

    "Jan"

  ],

  "wheel_press": [

    "35",

    "19"

  ],

  "max-weight": [

    "4000",

    "8"

  ],

  "transition_plan": [

    "",

    null

  ],

  "number_of_occurence": [

    5696,

    976

  ],

  "model": [

    "sedan",

    "street"


}

我想过滤任何对象键以仅获取该键的相应值。到目前为止,在搜索 stackoverflow 后仍然无法找到类似的问题。我试过使用


data.filter(type ==='car')

我得到的错误是


.filter is not a function

预期的输出是如果我过滤 type === 'car' 那么它应该只显示


{

  "type": [

    "car"

  ],

  "wheels": [

    "4"

  ],

  "open": [

    "Jan"

  ],

  "wheel_press": [

    "35"

  ],

  "max-weight": [

    "4000"

  ],

  "transition_plan": [

    ""

  ],

  "number_of_occurence": [

    5696

  ],

  "model": [

    "sedan"


}


慕哥9229398
浏览 150回答 1
1回答

白板的微信

您可以编写一个函数来查找给定属性内的值的索引,然后使用Object.fromEntries(),Object.keys()并Array.map()创建一个新对象,如下所示var data={type:["car","bike"],wheels:["4","2"],open:["Jan","Jan"],wheel_press:["35","19"],"max-weight":["4000","8"],transition_plan:["",null],number_of_occurence:[5696,976],model:["sedan","street"]};const getFilteredObject = (property, value) => {  const index = data[property].indexOf(value)    return Object.fromEntries(Object.keys(data).map(key => ([key, data[key][index]])))}const filteredObject = getFilteredObject('type','car');console.log(filteredObject)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript