I'm trying to manipulate data, and I'd need a solution for this
Tried mapping in different ways, but none of them worked.
This is the input data:
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
}
]
}
Here is the expected result:
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
}
]
}
]
You can use Object.entries and map
Here idea is :-
object.entries
get the key value from object and map on them to change it to needed format Key
is used as year
property in desired structure and value
is used as 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)
You could map the values and destructure the year from the rest object.
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; }
try this
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.