我有以下对象:
let obj = {
"productData": [{
"id": 0,
"daily_netProfit": 1.35208688924,
"daily_grossProfit": 1.35448688924,
"daily_costs": 0.0024,
"created_at": "2018-06-18"
},
{
"id": 1,
"daily_netProfit": 1.35208688924,
"daily_grossProfit": 1.35448688924,
"daily_costs": 0.0024,
"created_at": "2018-06-19"
}
]
}
let dataSet = obj.productData.map((item, i) => [
item.daily_netProfit,
item.daily_grossProfit,
item.daily_costs,
item.created_at,
])
console.log(dataSet)
如您所见,上面的map函数构造了一个数组中的数组。但是,带有对象的最终结果数组应如下所示:
[{
daily_netProfit: 1.35208688924,
daily_grossProfit: 1.35448688924,
daily_costs: 0.0024,
day: "2018-06-18"
},
{
daily_netProfit: 1.35208688924,
daily_grossProfit: 1.35448688924,
daily_costs: 0.0024,
day: "2018-06-19"
}
],
是否有一个map函数来构造上面的array-object?
感谢您的回复!
答案 0 :(得分:3)
您可以映射对象。
var obj = { productData: [{ id: 0, daily_netProfit: 1.35208688924, daily_grossProfit: 1.35448688924, daily_costs: 0.0024, created_at: "2018-06-18" }, { id: 1, daily_netProfit: 1.35208688924, daily_grossProfit: 1.35448688924, daily_costs: 0.0024, created_at: "2018-06-19" }] },
dataSet = obj.productData.map(
({ daily_netProfit, daily_grossProfit, daily_costs, created_at: day }) =>
({ daily_netProfit, daily_grossProfit, daily_costs, day }))
console.log(dataSet)
.as-console-wrapper { max-height: 100% !important; top: 0; }
使用对象的rest语法(对于最新的JS)甚至更短
var obj = { productData: [{ id: 0, daily_netProfit: 1.35208688924, daily_grossProfit: 1.35448688924, daily_costs: 0.0024, created_at: "2018-06-18" }, { id: 1, daily_netProfit: 1.35208688924, daily_grossProfit: 1.35448688924, daily_costs: 0.0024, created_at: "2018-06-19" }] },
dataSet = obj.productData.map(({ id, created_at: day, ...rest }) => ({ ...rest, day }));
console.log(dataSet);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:1)
您正在创建数组而不是对象。改为创建对象。您可以使用参数解构来挑选所需的部件,然后使用对象初始化器来创建新对象:
let obj = {
"productData": [{
"id": 0,
"daily_netProfit": 1.35208688924,
"daily_grossProfit": 1.35448688924,
"daily_costs": 0.0024,
"created_at": "2018-06-18"
},
{
"id": 1,
"daily_netProfit": 1.35208688924,
"daily_grossProfit": 1.35448688924,
"daily_costs": 0.0024,
"created_at": "2018-06-19"
}
]
};
let dataSet = obj.productData.map(
({
daily_netProfit,
daily_grossProfit,
daily_costs,
created_at
}) => ({
daily_netProfit,
daily_grossProfit,
daily_costs,
created_at
})
);
console.log(dataSet)

.as-console-wrapper {
max-height: 100% !important;
}