【发布时间】:2020-11-07 23:49:42
【问题描述】:
我再次陷入对以下内容的一些扁平化和重命名中。 我得到了什么:
test = [
{
date: '2020-03-30',
station: {
id: 0,
name: 'some description'
},
firstValues: [
{
result: 1,
type: 4,
max: 18,
min: 1,
},
{
result: 2,
type: 5,
max: 15,
min: 2,
}
],
lastValues: [
{
result: 1,
type: 3,
max: 17,
min: 1
},
{
result: 2,
type: 8,
max: 20,
min: 2
}
],
iD: 'xxx3',
count: 1
},
{
next object with same structure
}
]
我想达到的目标:
test = [
{
date: '2020-03-30',
station: 'some description',
first_E01_result: 1,
first_E01_type: 4,
first_E01_max: 18,
first_E01_min: 1,
first_E02_result: 2,
first_E02_type: 5,
first_E02_max: 15,
first_E02_min: 2,
last_E01_result: 1,
last_E01_type: 3,
last_E01_max: 17,
last_E01_min: 1,
last_E02_result: 2,
last_E02_type: 8,
last_E02_max: 20,
last_E02_min: 2,
iD: 'xxx3',
count: 1
},
{
next object with same structure
}
]
我很清楚我的方法是不正确的。到目前为止,我尝试了不同的方法,但无法正常工作。我又完全陷入了寻找正确方法的困境,因为我确实遇到了两个主要问题:
如何区分第一个值和最后一个值? (切换大小写或 if 和 if else?) 和 如何从站对象访问名称属性并将其分配给“站”的键
这是我的最后一种方法,但仍然缺少解决上述问题的正确代码:
convertTest(input) {
return input.map(obj => {
const obj1 = {};
const obj2 = {};
for (const prop in obj) {
if (obj.hasOwnProperty(prop) && Array.isArray(obj[prop])) {
for (let i = 0; i < obj[prop].length; i++) {
for (const [key, value] of Object.entries(obj[prop][i])) {
const name = 'first_EO' + (i + 1).toString() + '_' + key;
obj2[name] = value;
}
}
} else {
obj1[prop] = obj[prop];
}
const dataconverted = Object.assign({}, obj1, obj2);
return dataconverted;
}
});
}
【问题讨论】:
-
您对
convertTest函数的输入是什么?正确的输入可以帮助您更好地了解您要做什么
标签: javascript arrays rename flatten