按属性过滤嵌套对象

时间:2020-10-09 02:12:37

标签: javascript node.js arrays json rest

我正在使用一个(错误设计的)API,该API发送以下响应:

{
   "0" : {
      "name" : "John",
      "last_name" : "Doe"
   },
   "1" : {
      "name": "Mary",
      "last_name": "Ann"
   },
   [...]
}

您可能已经注意到,它是带有嵌套对象的大型JSON对象。由于它不是数组,因此无法使用.filter()。那么,如何通过嵌套对象属性(例如namelast_name)过滤这个大对象?

1 个答案:

答案 0 :(得分:1)

您可以使用Object.values(type).flat()将其设置为数组。然后它将使对象值成为单个数组。

const input1 = {
   "0" : {
      "name" : "John",
      "last_name" : "Doe"
   },
   "1" : {
      "name": "Mary",
      "last_name": "Ann"
   }
}

function search(input, key) {
  return Object.values(input).flat().filter(({ name }) => name === key);
}

console.log(search(input1, "John"));