我有一个对象,它有一些字段是数组(字符串或其他对象(,我试图将此对象转换为csv,但对于具有数组的情况,我希望csv在数组的情况下是垂直的(而不是水平的,并将索引附加到字段名(。在尝试了几个npm库和在线转换器后,我无法实现我想要的,带有数组的字段只是用它们的索引作为列名编写的。
作为一种变通方法,我现在试图将对象展平以充实数组字段,然后将其转换为csv,但展平仍然保持数组原样,输出中的对象数量没有变化。我尝试过lodash、下划线、Array的flat等库,但都没有成功。
有没有一种方法可以实现这一点,要么直接转换为csv,要么至少将对象变平。
我的实物样本低于
[
{
"field1": "Hello",
"field2": [
"list item 1",
"list item 2",
"list item 3"
],
"field3": [],
"field4": [{
"subfield1": "World",
"subfield2": "!"
}, {
"subfield1": "Again",
"subfield2": "?"
}]
}
]
基于这个示例对象,我的输出应该是.
[
{
"field1": "Hello",
"field2": "list item 1",
"field3": null, // or [], in this case it wouldn't matter
"field4": {
"subfield1": "World",
"subfield2": "!"
}
},
{
"field1": "Hello",
"field2": "list item 1",
"field3": null,
"field4": {
"subfield1": "Again",
"subfield2": "?"
}
},
{
"field1": "Hello",
"field2": "list item 2",
"field3": null,
"field4": {
"subfield1": "World",
"subfield2": "!"
}
},
{
"field1": "Hello",
"field2": "list item 2",
"field3": null,
"field4": {
"subfield1": "Again",
"subfield2": "?"
}
},
{
"field1": "Hello",
"field2": "list item 3",
"field3": null,
"field4": {
"subfield1": "World",
"subfield2": "!"
}
},
{
"field1": "Hello",
"field2": "list item 3",
"field3": null,
"field4": {
"subfield1": "Again",
"subfield2": "?"
}
}
]
有没有什么图书馆可以让我做到这一点?
除了空数组之外,您可以对所有值使用笛卡尔乘积。
function getCartesian(object) {
return Object.entries(object).reduce((r, [k, v]) => {
const temp = [];
if (Array.isArray(v) && !v.length) v = null;
r.forEach(s =>
(Array.isArray(v) ? v : [v]).forEach(w =>
(w && typeof w === 'object' ? getCartesian(w) : [w]).forEach(x =>
temp.push(Object.assign({}, s, { [k]: x }))
)
)
);
return temp;
}, [{}]);
}
const
data = { field1: "Hello", field2: ["list item 1", "list item 2", "list item 3"], field3: [], field4: [{ subfield1: "World", subfield2: "!" }, { subfield1: "Again", subfield2: "?" }] },
result = getCartesian(data);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }