从对象内部的对象数组到数组内部的对象数组处理数据

时间:2019-05-14 11:22:39

标签: javascript arrays json

我正在尝试处理数据,为此我需要一个解决方案

尝试以不同的方式进行映射,但没有一个起作用。

这是输入数据:

   data_input = {
    2000: [{
            _id: 0,
            name: "Jeff",
            value: 130,
            year: 2000
        },
        {
            _id: 1,
            name: "Bill",
            value: 30,
            year: 2000
        }
    ],
    2001: [{
            _id: 0,
            name: "Jeff",
            value: 20,
            year: 2001
        },
        {
            _id: 1,
            name: "Bill",
            value: 100,
            year: 2001
        }
    ]
 }

这是预期的结果:

   data_output = [{
        year: 2000,
        year_data: [{
                _id: 0,
                name: "Jeff",
                value: 130
            },
            {
                _id: 1,
                name: "Bill",
                value: 30
            }
        ]
    },
    {
        year: 2001,
        year_data: [{
                _id: 0,
                name: "Jeff",
                value: 20
            },
            {
                _id: 1,
                name: "Bill",
                value: 100
            }
        ]
    }
 ]

3 个答案:

答案 0 :(得分:4)

您可以使用Object.entriesmap

这里的想法是:-

  • 使用object.entries从对象获取键值并将其映射到其上以将其更改为所需的格式
  • Key用作所需结构的year属性,而value用作year_data

let data = {2000: [{ _id: 0, name: "Jeff", value:130, year: 2000 }, { _id: 1, name: "Bill", value:30, year: 2000 } ] , 2001 : [{ _id: 0, name: "Jeff", value: 20, year: 2001 }, {_id:1, name: "Bill", value: 100, year: 2001 } ]}

let final = Object.entries(data).map(([year, year_data]) => ({ year, year_data: year_data.map(({year,...rest})=>rest)}))

console.log(final)

答案 1 :(得分:0)

您可以映射值并从其余对象中破坏年份。

var data_input = { 2000: [{ _id: 0, name: "Jeff", value: 130, year: 2000 }, { _id: 1, name: "Bill", value: 30, year: 2000 }], 2001: [{ _id: 0, name: "Jeff", value: 20, year: 2001 }, { _id: 1, name: "Bill", value: 100, year: 2001 }] },
    result = Object
        .values(data_input)
        .map(a => ({ year: a[0].year, year_data: a.map(({ year, ...rest }) => rest) }));

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

答案 2 :(得分:0)

尝试

 data_input = {
    2000: [{
            _id: 0,
            name: "Jeff",
            value: 130,
            year: 2000
        },
        {
            _id: 1,
            name: "Bill",
            value: 30,
            year: 2000
        }
    ],
    2001: [{
            _id: 0,
            name: "Jeff",
            value: 20,
            year: 2001
        },
        {
            _id: 1,
            name: "Bill",
            value: 100,
            year: 2001
        }
    ]
 }

var output = Object.keys(data_input).map(item => {
  let year_data = data_input[item].map(data => {
    delete data.year
    return data
  });
  return {
    year: item,
    year_data:year_data
  }
});

console.log(output);