gpt4 book ai didi

javascript - 将嵌套 JSON 展平为不带索引的唯一对象数组

转载 作者:行者123 更新时间:2023-12-02 17:57:50 25 4
gpt4 key购买 nike

我有一个简单的嵌套对象,我需要将其展平才能将其插入到我的数据库中。

const input = {
name: "Benny",
department: {
section: "Technical",
branch: {
timezone: "UTC",
},
},
company: [
{
name: "SAP",
customers: ["Ford-1", "Nestle-1"],
},
{
name: "SAP",
customers: ["Ford-2", "Nestle-2"],
},
],
};

期望的结果是这样的,数组中的每个值都会生成一个存储在数组中的新子对象:

[
{
name: "Benny",
"department.section": "Technical",
"department.branch.timezone": "UTC",
"company.name": "SAP",
"company.customers": "Ford-1",
},
{
name: "Benny",
"department.section": "Technical",
"department.branch.timezone": "UTC",
"company.name": "SAP",
"company.customers": "Nestle-1",
},
{
name: "Benny",
"department.section": "Technical",
"department.branch.timezone": "UTC",
"company.name": "SAP",
"company.customers": "Ford-2",
},
{
name: "Benny",
"department.section": "Technical",
"department.branch.timezone": "UTC",
"company.name": "SAP",
"company.customers": "Nestle-2",
},
]

而不是下面的结果,所有字段都存储在带有索引的单个对象中:

{
name: 'Benny',
'department.section': 'Technical',
'department.branch.timezone': 'UTC',
'company.0.name': 'SAP',
'company.0.customers.0': 'Ford-1',
'company.0.customers.1': 'Nestle-1',
'company.1.name': 'SAP',
'company.1.customers.0': 'Ford-2',
'company.1.customers.1': 'Nestle-2'
}

我的代码如下所示:

function flatten(obj) {
let keys = {};
for (let i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == "object") {
let flatObj = flatten(obj[i]);
for (let j in flatObj) {
if (!flatObj.hasOwnProperty(j)) continue;
keys[i + "." + j] = flatObj[j];
}
} else {
keys[i] = obj[i];
}
}
return keys;
}

提前致谢!

最佳答案

您可以将数组的值作为笛卡尔积的一部分,并最终获得平面对象。

const
getArray = v => Array.isArray(v) ? v : [v],
isObject = v => v && typeof v === 'object',
getCartesian = object => Object.entries(object).reduce((r, [k, v]) => r.flatMap(s =>
getArray(v).flatMap(w =>
(isObject(w) ? getCartesian(w) : [w]).map(x => ({ ...s, [k]: x }))
)
), [{}]),
getFlat = o => Object.entries(o).flatMap(([k, v]) => isObject(v)
? getFlat(v).map(([l, v]) => [`${k}.${l}`, v])
: [[k, v]]
),
input = { name: "Benny", department: { section: "Technical", branch: { timezone: "UTC" } }, company: [{ name: "SAP", customers: ["Ford-1", "Nestle-1"] }, { name: "SAP", customers: ["Ford-2", "Nestle-2"] }] },
result = getCartesian(input).map(o => Object.fromEntries(getFlat(o)));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 将嵌套 JSON 展平为不带索引的唯一对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75238476/

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