尝试根据特定字段键展平嵌套对象

Attempting to flatten nested objects based on a specific field key

我希望通过数组进行映射,获取指定字段的 key/value,然后将其合并到主对象中。

目前我的阵列看起来像:

const data = [
   {
      "id": "3QXNO4SDo08FgAfQy3z5",
      "title": "Team One",
      "scores": [
         {
            "id": "DbkZljn22YSGVBLxiT4o",
            "score": 88
         },
         {
            "id": "v7ss2ypT4qf9RIvIynJp"
            "score": 5,
         }
      ]
   },
   {
      "id": "EmoL3dlPWpOPPiLixIYJ",
      "title": "Team Two",
      "scores": [
         {
            "id": "DbkZljn22YSGVBLxiT4o",
            "score": 77,
         },
         {
            "id": "v7ss2ypT4qf9RIvIynJp",
            "score": 0,
         }
      ]
   }
]

我需要将其简化为:

[
   {
      "id": "3QXNO4SDo08FgAfQy3z5",
      "title": "Team One",
      "DbkZljn22YSGVBLxiT4o": 88,
      "v7ss2ypT4qf9RIvIynJp": 5,
   },
   {
      "id": "EmoL3dlPWpOPPiLixIYJ",
      "title": "Team Two",
      "DbkZljn22YSGVBLxiT4o": 77,
      "v7ss2ypT4qf9RIvIynJp": 0,
   }
]

获取分数的唯一 ID 并将其用作我的对象键。

我想这需要嵌套循环才能得到结果。我会 post 我的编码尝试,但它们存在严重缺陷且令人困惑。

你的问题不清楚.. 但这个答案可能对您有所帮助

const data= [
   {
      "id": "3QXNO4SDo08FgAfQy3z5",
      "title": "Team One",
      "scores": [
         {
            "id": "DbkZljn22YSGVBLxiT4o",
            "score": 88
         },
         {
            "id": "v7ss2ypT4qf9RIvIynJp"
            "score": 5,
         }
      ]
   },
   {
      "id": "EmoL3dlPWpOPPiLixIYJ",
      "title": "Team Two",
      "scores": [
         {
            "id": "DbkZljn22YSGVBLxiT4o",
            "score": 77,
         },
         {
            "id": "v7ss2ypT4qf9RIvIynJp",
            "score": 0,
         }
      ]
   }
]

点击数据字段:

const array = [];

function handleSelect(id) {

const copyData = [...data];
const foundItems =  copyData.map(item => item.id === id);

array.push(foundItems)

}

最终数组为:

const array = [
   {
      "id": "3QXNO4SDo08FgAfQy3z5",
      "title": "Team One",
      "DbkZljn22YSGVBLxiT4o": 88,
      "v7ss2ypT4qf9RIvIynJp": 5,
   },
   {
      "id": "EmoL3dlPWpOPPiLixIYJ",
      "title": "Team Two",
      "DbkZljn22YSGVBLxiT4o": 77,
      "v7ss2ypT4qf9RIvIynJp": 0,
   }
]
const flattenedArray = data.map((dt) => {
  let ar = [];
  dt.scores.forEach((n, i) => (ar = { ...ar, [n.id]: n.score }));
  return { ...dt, ...ar };
});

Returns 所需的展平数组。

您可以结合使用 Array#mapArray#reduce 以获得所需的输出。

const mapped = data.map(({ scores, ...rest }) => ({
  ...rest,
  ...scores.reduce((output, score) => ({ ...output, [score.id]: score.score }), {})
}));