我想知道是否可以规范这样的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”等数组对象? :)

最佳答案

您确实不需要为此使用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));

08-05 04:26