我有这个对象:
{
"value": "face",
"next": [
{
"value": "tace",
"next": [
{
"value": "tale",
"next": [
{
"value": "talk",
"next": []
}
]
},
{
"value": "tack",
"next": [
{
"value": "talk",
"next": []
}
]
}
]
},
{
"value": "fack",
"next": [
{
"value": "tack",
"next": [
{
"value": "talk",
"next": []
}
]
},
{
"value": "falk",
"next": [
{
"value": "talk",
"next": []
}
]
}
]
}
]
}
迭代遍历并创建此数组数组的最佳方法是什么:
[
["face", "tace", "tale", "talk"],
["face", "tace", "tack", "talk"],
["face", "fack", "tack", "talk"],
["face" ,"fack", "falk", "talk"]
]
我基本上想通过遍历对象的每个分支并为每个分支生成字符串数组来将对象“展平”为数组格式。
答案 0 :(得分:1)
您可以通过使用def append(df, c):
table_name = 'ddf.ddf_actuals'
columns_list = df.columns.tolist()
columns_list_query = f'({(",".join(columns_list))})'
sr_columns_list = [f'Source.{i}' for i in columns_list]
sr_columns_list_query = f'({(",".join(sr_columns_list))})'
up_columns_list = [f'{i}=Source.{i}' for i in columns_list]
up_columns_list_query = f'{",".join(up_columns_list)}'
rows_to_insert = [row.tolist() for idx, row in final_list.iterrows()]
rows_to_insert = str(rows_to_insert).replace('[', '(').replace(']', ')')[1:][:-1]
query = f"MERGE INTO {table_name} as Target \
USING (SELECT * FROM \
(VALUES {rows_to_insert}) \
AS s {columns_list_query}\
) AS Source \
ON Target.stationcode=Source.stationcode AND Target.date=Source.date \
WHEN NOT MATCHED THEN \
INSERT {columns_list_query} VALUES {sr_columns_list_query} \
WHEN MATCHED THEN \
UPDATE SET {up_columns_list_query};"
c.execute(query)
c.commit()
方法创建递归函数来做到这一点,该方法将存储先前的值,并且当reduce
属性中没有元素时,它将当前复制推入结果数组。
next
答案 1 :(得分:1)
您可以使用独立的递归函数并收集最后一项,并为每个级别构建一个由给定值组成的数组。
const
flat = (value, next) => next
.reduce((r, { value, next }) => {
if (next.length) r.push(...flat(value, next));
else r.push([value]);
return r;
}, [])
.map(q => [value, ...q]);
var data = { value: "face", next: [{ value: "tace", next: [{ value: "tale", next: [{ value: "talk", next: [] }] }, { value: "tack", next: [{ value: "talk", next: [] }] }] }, { value: "fack", next: [{ value: "tack", next: [{ value: "talk", next: [] }] }, { value: "falk", next: [{ value: "talk", next: [] }] }] }] },
result = flat(data.value, data.next);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 2 :(得分:1)
您可以对Array.forEach()
使用递归来迭代next
属性,并添加前面的项目。 next
为空时,将所有内容弄平,然后推入结果:
const flatAll = (data) => {
const result = [];
const fn = ({ value, next }, prev = []) => {
if(next.length) next.forEach(o => fn(o, [prev, value]));
else result.push([prev, value].flat(Infinity));
};
fn(data);
return result;
}
const data = {"value":"face","next":[{"value":"tace","next":[{"value":"tale","next":[{"value":"talk","next":[]}]},{"value":"tack","next":[{"value":"talk","next":[]}]}]},{"value":"fack","next":[{"value":"tack","next":[{"value":"talk","next":[]}]},{"value":"falk","next":[{"value":"talk","next":[]}]}]}]};
const result = flatAll(data);
console.log(result);