gpt4 book ai didi

javascript - 是否可以用 "excel-like"标准化 "normalizr"JSON(没有 id)?

转载 作者:行者123 更新时间:2023-11-28 04:43:57 25 4
gpt4 key购买 nike

我想知道是否可以标准化这样的 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));

关于javascript - 是否可以用 "excel-like"标准化 "normalizr"JSON(没有 id)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43544913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com