我有以下 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"}
1 回答
白板的微信
TA贡献1883条经验 获得超3个赞
您可以编写一个函数来查找给定属性内的值的索引,然后使用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)
添加回答
举报
0/150
提交
取消