如何改变对象结构

时间:2017-07-24 16:47:07

标签: javascript object

我想将JavaScript对象的结构更改为另一个。我的问题是,对于每个对象,我必须创建最多三个不同的对象:

我的意见:

[
  {date: "21-05", cash: "500", card: "200", points: "100"},
  {date: "26-05", card: "100", points: "50"}
]

期望的输出:

[
  {date: "21-05", amount: "500", paymentType: cash }, 
  {date: "21-05", amount: "200", paymentType: card }, 
  {date: "21-05", amount: "200", paymentType: points }, 
  {date: "26-05", amount: "100", paymentType: card }, 
  {date: "26-05", amount: "50",  paymentType: points }
]

现金,卡片,积分是全球const

2 个答案:

答案 0 :(得分:0)

您可以使用几个for循环:

const data = [
    {date:"21-05", cash: "500", card:"200", points:"100"},
    {date: "26-05", card:"100", points:"50"}
];

const result = [];
for (let row of data) {
    for (let key in row) {
        if (key !== 'date') {
            result.push({
                data: row.date,
                amount: row[key],
                paymentType: key
            });
        }
    }
}

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

您可以迭代数组和键并检查是否date,然后使用数据构建新对象。收集直到访问所有对象。

var data = [{ date: "21-05", cash: "500", card: "200", points: "100" }, { date: "26-05", card: "100", points: "50" }],
    result = data.reduce(function (r, o) {
        Object.keys(o).forEach(function (k) {
            if (k !== 'date') {
                r.push({ date: o.date, amount: o[k], paymentType: k });
            }
        });
        return r;
    }, []);
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }