【发布时间】:2019-10-16 22:31:47
【问题描述】:
我有一个下面的数据结构,我需要从中提取列,这是一个数组,我需要用键和实际标签名称构建一个对象。
有没有更好的方法来实现这一点。
任何帮助表示赞赏
let data = {
"section1": {
"forms": [
{
"fields": [
{
"columnName": "test1",
"label": [
{
"actualLabel": "Test 1"
}
]
},
{
"columnName": "test2",
"label": [
{
"actualLabel": "Test 2"
}
]
},
{
"columnName": "test0",
"label": [
{
"actualLabel": "Test 0"
}
]
}
]
},
{
"fields": [
{
"columnName": "test6",
"label": [
{
"actualLabel": "Test 6"
}
]
},
{
"columnName": "test3",
"label": [
{
"actualLabel": "Test 3"
}
]
},
{
"columnName": "test10",
"label": [
{
"actualLabel": "Test 10"
}
]
}
]
},
{
"fields": [
{
"columnName": "test15",
"label": [
{
"actualLabel": "Test 15"
}
]
},
{
"columnName": "test",
"label": [
{
"actualLabel": "Test 6"
}
]
},
{
"columnName": "test7",
"label": [
{
"actualLabel": "Test 7"
}
]
}
]
}
]
},
"section2": {
"forms": [
{
"fields": [
{
"columnName": "test1",
"label": [
{
"actualLabel": "Test 1"
}
]
},
{
"columnName": "test2",
"label": [
{
"actualLabel": "Test 2"
}
]
},
{
"columnName": "test0",
"label": [
{
"actualLabel": "Test 0"
}
]
}
]
},
{
"fields": [
{
"columnName": "test3",
"label": [
{
"actualLabel": "Test 3"
}
]
},
{
"columnName": "test4",
"label": [
{
"actualLabel": "Test 4"
}
]
},
{
"columnName": "test10",
"label": [
{
"actualLabel": "Test 10"
}
]
}
]
},
{
"fields": [
{
"columnName": "test5",
"label": [
{
"actualLabel": "Test 5"
}
]
},
{
"columnName": "test6",
"label": [
{
"actualLabel": "Test 6"
}
]
},
{
"columnName": "test7",
"label": [
{
"actualLabel": "Test 7"
}
]
}
]
}
]
},
"section3": {
"forms": [
{
"fields": [
{
"columnName": "test1",
"label": [
{
"actualLabel": "Test 1"
}
]
},
{
"columnName": "test2",
"label": [
{
"actualLabel": "Test 2"
}
]
},
{
"columnName": "test0",
"label": [
{
"actualLabel": "Test 0"
}
]
}
]
},
{
"fields": [
{
"columnName": "test3",
"label": [
{
"actualLabel": "Test 3"
}
]
},
{
"columnName": "test 4",
"label": [
{
"actualLabel": "Test 4"
}
]
},
{
"columnName": "test10",
"label": [
{
"actualLabel": "Test 10"
}
]
}
]
},
{
"fields": [
{
"columnName": "test15",
"label": [
{
"actualLabel": "Test 15"
}
]
},
{
"columnName": "test6",
"label": [
{
"actualLabel": "Test 6"
}
]
},
{
"columnName": "test7",
"label": [
{
"actualLabel": "Test 7"
}
]
}
]
}
]
}
}
let extractColumns = ['test1', 'test2', 'test7', 'test15']
let result = Object.entries(data).reduce(
(initial, [key, { forms }]) => {
forms.forEach(({ fields }) => {
fields.forEach(
({
columnName,
label: {
0: { actualLabel },
},
}) => {
if (extractColumns.indexOf(columnName) > -1) {
initial[columnName] = {
actualLabel,
};
}
},
);
});
return initial;
},
{},
);
console.log(result)
【问题讨论】:
标签: javascript arrays object ecmascript-6