这是第一个关键人物中包含所需对象的所有属性的列表,在后面的关键人物中包含该行中每个属性的值。:
[
[
"goalId",
"holderId",
"balance",
"taxes",
"netBalance",
"investmentIncome"
],
[
"1",
"1",
"33333333",
"150",
"150",
"1"
],
[
"5",
"5",
"1000",
"150",
"150",
"1"
],
[
"7",
"7",
"1000",
"150",
"150",
"1"
],
[
"11",
"12",
"1000",
"150",
"150",
"1"
],
[
""
]
]
而且我想将上面的列表变成这样的对象列表:
[
{
"goalId":1,
"holderId":1,
"balance":33333333,
"taxes":150,
"netBalance":150,
"investmentIncome":1
},
{
"goalId":5,
"holderId":5,
"balance":1000,
"taxes":150,
"netBalance":150,
"investmentIncome":1
},
{
"goalId":7,
"holderId":7,
"balance":1000,
"taxes":150,
"netBalance":150,
"investmentIncome":1
},
{
"goalId":11,
"holderId":12,
"balance":1000,
"taxes":150,
"netBalance":150,
"investmentIncome":1
}
]
我已经完成了,但是我认为有更好的方法。代码是这样的:
// Assuming that the variable already has the list loaded
const attributes = unformattedList[0];
unformattedList.splice(0, 1);
const arrayOfObjects = unformattedList.map(rawValue => {
const object = {};
rawValue.map((value, index) => {
object[attributes[index]] = value;
});
return object;
});
如果您唯一的用例是迭代并产生副作用,则不应该使用.map()
-.forEach()
对于该任务而言更好。但是,如果您按预期使用(例如,使用它返回的新数组),仍然可以使用.map()
处理此类问题。首先,通过使用.shift()
从数组中弹出第一个元素,可以获取对象的键。然后,您可以.map()
将每个内部值数组分配给一个对象(使用Object.assign()
形成),该对象包含内部数组中的所有值: