从对象的嵌套数组中提取对象

时间:2019-08-22 17:44:17

标签: javascript

我有以下数据,这些数据是嵌套对象的数组:

"categories": [
  {
   "id": 1,
   "name": "Category 1",
   "years": [
    { "id": 1, "name": "1" },
    { "id": 2, "name": "2" }
   ]
  },
  {
   "id": 2,
   "name": "Category 2",
   "years": [
    { "id": 2, "name": "2" },
    { "id": 3, "name": "3" }
   ]
  }
 ]

我想在一个单独的数组(期望的输出)中提取唯一的years

[
  { "id": 1, "name": "1" },
  { "id": 2, "name": "2" },
  { "id": 3, "name": "3" },
]

当我绘制年份时,我得到了一个数组数组,应该如何为years提取唯一对象?

let years = categories.map( (c) => { return c.years })

2 个答案:

答案 0 :(得分:2)

您可以使用reduceMap

let data = [{"id": 1,"name": "Category 1","years": [{ "id": 1, "name": "1" },{ "id": 2, "name": "2" }]},{"id": 2,"name": "Category 2","years": [{ "id": 2, "name": "2" },{ "id": 3, "name": "3" }]}]
  
let final = data.reduce((op,{years}) => {
  years.forEach(({id, name}) => {
    let key = id + '-' + name
    op.set(key, op.get(key) || {id, name})
  })
  return op
},new Map())

console.log([...final.values()])

答案 1 :(得分:2)

您可以使用Map,以id为键,在categoriesyears上使用reduce(),从值数组中过滤掉重复的年份。使用地图作为累加器:

const categories = [{
    "id": 1,
    "name": "Category 1",
    "years": [
      { "id": 1, "name": "1" },
      { "id": 2, "name": "2" }
    ]
  },
  {
    "id": 2,
    "name": "Category 2",
    "years": [
      { "id": 2, "name": "2" },
      { "id": 3, "name": "3" }
    ]
  }
];

const years = categories.reduce(
  (map, category) => category.years.reduce(
    (map, year) => map.set(year.id, year),
    map
  ),
  new Map()
);

console.log([...years.values()]);