1

我想知道是否可以标准化这样的 JSON:

{
"rows": [{
        "cells": [{
                "value": "Column Name 1"
            },
            {
                "value": "Column Name 2"
            },
            {
                "value": "Column Name 3"
            },
            {
                "value": "Column Name 4"
            }
        ]
    },
    {
        "cells": [{
                "value": "Second Row Thing1"
            },
            {
                "value": "Second Row Thing2"
            },
            {
                "value": "Second Row Thing3"
            },
            {
                "value": "Second Row Thing4"
            }
        ]
    },
    {
        "cells": [{
                "value": "Third Row Thing1"
            },
            {
                "value": "Third Row Thing2"
            },
            {
                "value": "Third Row Thing3"
            },
            {
                "value": "Third Row Thing4"
            }
        ]
    }
]

}

变成如此漂亮的格式:

{
    "rows": [{
            "Column Name 1": "Second Row Thing1"
            "Column Name 2": "Second Row Thing1"
            "Column Name 3": "Second Row Thing1"
            "Column Name 4": "Second Row Thing1"
        },
        {
            "Column Name 1": "Third Row Thing1"
            "Column Name 2": "Third Row Thing1"
            "Column Name 3": "Third Row Thing1"
            "Column Name 4": "Third Row Thing1"
        }

    ]
}

基本上我想把第一行的数据当作列名来对待。然后使用这些列名作为我的行对象中键的名称。可以用“normalizr”做这样的事情吗?或者我应该深入研究“map”、“foreach”等数组的东西吗?:)

4

1 回答 1

0

你真的不需要 Normalizr (你不应该使用它,因为它不起作用)。Normalizr 用于嵌套数据:具有对其他实体的引用的实体(例如嵌入在推文中的用户)。

Map/Reduce 非常适合这样的事情。这是一个完全符合您要求的片段。

const data = { "rows": [
  { "cells": [{ "value": "Column Name 1" }, { "value": "Column Name 2" }, { "value": "Column Name 3" }, { "value": "Column Name 4" } ]},
  { "cells": [{ "value": "Second Row Thing1" }, { "value": "Second Row Thing2" }, { "value": "Second Row Thing3" }, { "value": "Second Row Thing4" } ] },
  { "cells": [{ "value": "Third Row Thing1" }, { "value": "Third Row Thing2" }, { "value": "Third Row Thing3" }, { "value": "Third Row Thing4" } ] }
]};

// Get an array of the values of the first row
const columns = data.rows[0].cells.map(({ value }) => value);

// slice = take all rows except the first
// mapp each array of cells
const normalizedData = data.rows.slice(1).map(({ cells }) => {
  // reduce = converts the array of cells into an object map
  return cells.reduce((memo, { value }, i) => {
    memo[columns[i]] = value;
    return memo;
  }, {});
});

console.log(JSON.stringify(normalizedData, null, 2));

于 2017-04-21T15:43:14.367 回答