gpt4 book ai didi

带有子对象的 JavaScript 对象需要转换为类似 SQL 的数组(nosql 数据格式转换为 sql)

转载 作者:行者123 更新时间:2023-12-03 03:01:59 24 4
gpt4 key购买 nike

我有数据数组,其中一些属性是数组。我想展平该数组,因此所有属性都不是数组,如下所述。

输入

[{
"name": "James",
"education": [
{ "year": 2014, "degree": "MS" },
{ "year": 2012, "degree": "BS" }]
}, {
"name": "Bond",
"education": [
{ "year": 2011, "degree": "MS" },
{ "year": 2009, "degree": "BS" }]
}]

输出

[
{"name":"James","education_year":2014,"education_degree":"MS"},
{"name":"James","education_year":2012,"education_degree":"BS"},
{"name":"Bond","education_year":2011,"education_degree":"MS"},
{"name":"Bond","education_year":2009,"education_degree":"BS"}
]

https://sqlify.io/convert当我要求它转换为 CSV 格式时,它会这样做。但我无法使用该服务。

有什么办法可以产生所需的输出,

最佳答案

使用 Array#map 进行迭代,然后将 education 映射到请求格式的新对象。使用 spread 展平结果和 Array#concat :

使用 Object#assign 创建对象。在分配内部,Array#将每个属性映射为所需的格式,然后展开:

const data = [{
"name": "James",
"education": [
{ "year": 2014, "degree": "MS" },
{ "year": 2012, "degree": "BS" }]
}, {
"name": "Bond",
"education": [
{ "year": 2011, "degree": "MS" },
{ "year": 2009, "degree": "BS" }]
}];

const result = [].concat(...data.map(({ name, education }) =>
education.map(({ year, degree }) => ({ name, education_year: year, education_degree: degree })
)));

console.log(result);

可以处理对象中的多个子数组的通用版本:

const data = [{"name":"James","lname":"Parker","education":[{"year":2014,"degree":"MS"},{"year":2012,"degree":"BS"}],"job":[{"year":2017,"title":"senior developer"},{"year":2017,"title":"developer"},{"year":2014,"title":"junior"}]},{"name":"Bond","lname":"Peter","education":[{"year":2011,"degree":"MS"},{"year":2009,"degree":"BS"}],"job":[{"year":2014,"title":"ninja"},{"year":2012,"title":"rogue"}]}];

const createKey = (prefix, key) => `${prefix}_${key}`;

const result = [].concat(...data.map((el) =>
Object.entries(el)
.map(([k, v]) => Array.isArray(v) ?
v.map((o) => Object.entries(o).reduce((r, [key, val]) => Object.assign(r, { [createKey(k, key)]: val }), {}))
:
{ [k]: v }
)
.reduce((r, s) =>
Array.isArray(s) ?
[].concat(...r.map((o) => s.map((q) => Object.assign({}, o, q))))
:
r.map((o) => Object.assign({}, o, s))
, [{}])
));

console.log(result);

关于带有子对象的 JavaScript 对象需要转换为类似 SQL 的数组(nosql 数据格式转换为 sql),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47340223/

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