我正在使用的应用程序具有以下结构:
collection {
user_entry_1 {
page_1_id {
input_1_id: someValue
input_2_id: anotherValue
},
page_2_id {
...
}
},
user_entry_2 {
...
如您所见,实际的所需值嵌套得很深。现在,我一直在为如何分组数据而奋斗了数小时,以使生成的对象看起来像以下内容:
collection {
page_1_id {
input_1_id: [value1, value2, value3...],
input_2_id: [value1, value2, value3...]
},
page_2_id {
input_3_id: [value1, value2, value3...],
...
如果有帮助,我正在处理分布在多个页面上的动态表单。我尝试过lodash,使用大量数组编写自定义意大利面条函数,等等,但不能简单地想出一种巧妙的方式来安排如上所示的数据。基本上,我需要将“最深的”嵌套值放入数组中,并且每个数组的键将是“输入”的键(多个相同的键,因为有多个用户)。
我只编码了几年,所以对我来说,这些类型的数组/对象操作并不是普通的香草。抱歉,如果很难阅读或我不清楚。
这是我的尝试:
const collection = {
user_entry_1: {
page_1_id: {
input_1_id: 'someValue',
input_2_id: 'anotherValue'
},
page_2_id: {
input_3_id: 'someValue' //,
//, enter other data here:
}
},
user_entry_2: {
page_1_id: {
input_1_id: 'someValue',
input_2_id: 'anotherValue'
},
page_2_id: {
input_3_id: 'someValue' //,
//, enter other data here:
}
}
};
//ENTER THE CODE YOU TRIED HERE:
您可以看到我的输出是这样的:
//Enter output from your attempt:
但是我希望:
//Enter desired output:
答案 0 :(得分:-1)
您可以使用reduce
函数来完成此操作。
var collection = { 'user_entry_1': { 'page_1_id': { 'input_1_id': 'someValue 1', 'input_2_id': 'anotherValue' }, 'page_2_id' : { 'input_1_id': 'someValue 2', 'input_2_id': 'anotherValue' }}, 'user_entry_2': { 'page_1_id': { 'input_1_id': 'someValue 2', 'input_2_id': 'anotherValue 2' }, 'page_2_id' : { 'input_1_id': 'someValue 2', 'input_2_id': 'anotherValue 2' }}};
var result = Object.entries(collection).reduce((acc, [key, value])=>{
for(const [k, v] of Object.entries(value)){
acc[k] = acc[k] || {};
Object.entries(v).forEach(([inputKey, inputValue])=>{
acc[k][inputKey] =acc[k][inputKey] || [];
acc[k][inputKey].push(inputValue);
})
}
return acc;
}, {});
console.log(result);