簡體   English   中英

操作 json 數據數組

[英]manipulating array of json data

我有一個項目,我必須從 GoogleSheet 文檔中獲取一些數據並將其發送到數據庫。 我從 googlesheet 文檔中獲取數據,但問題是數據的結構如何。

[
  {
    class: "A",
    name: "Alex",
    age: 13
  },
  {
    class: "A",
    name: "Mary",
    age: 14
  },
  {
    class: "B",
    name: "John",
    age: 13
  },
  {
    class: "B",
    name: "William",
    age: 12
  }
]

問題是我希望我的 JSON 對象看起來像這樣

[
  "A": {
    {
      name: "Alex",
      age: 13
    },
    {
      name: "Mary",
      age: 13
    }
  },
  "B": {
    {
      name: "John",
      age: 13
    },
    {
      name: "William",
      age: 13
    }
  }
]

知道我該怎么做嗎? 我想將我的對象分組到一個元素上,比如類。 所有具有相同類值的人都在同一個組/json 中。

您可以使用Array.reduce並對其進行格式化。

 let data = [{class:"A",name:"Alex",age:13},{class:"A",name:"Mary",age:14},{class:"B",name:"John",age:13},{class:"B",name:"William",age:12}]; //destructuring and renaming it to `_` as `class` is a pre-defined identifier in javascript const formatData = (data) => data.reduce((res, { class: _, ...rest }) => { //(res[_] || []) --> If the `class` prop is not already present in the res object, then using empty array //If already present spreading res[_] and adding the current object to the existing array res[_] = [...(res[_] || []), { ...rest }] return res; }, {}) console.log(formatData(data))
 .as-console-wrapper { max-height: 100% !important; }

您可以查看解構Destructuring Assignment以獲取有關解構和分配新變量名稱的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM