I have an array like this:
let array = [
{1: {
"date": "2014-04-23 00:00:00",
"volumetrie": "22458"
}},
{2: {
"date": "2014-05-02 00:00:00",
"volumetrie": "30585"
}},
{3: {
"date": "2014-03-27 00:00:00",
"volumetrie": "49536"
}}
]
But I need this like this:
let array = [
{
"date": "2014-04-23 00:00:00",
"volumetrie": "22458"
},
{
"date": "2014-05-02 00:00:00",
"volumetrie": "30585"
},
{
"date": "2014-03-27 00:00:00",
"volumetrie": "49536"
}
]
I tried to change this like:
array.forEach(function(e){
newData.push(e);
});
But this does not work. Push is not supported.
Next try was:
let newData = {};
array.forEach(function(e){
newData = {...newData, ...e};
});
No success. Any ideas how to get the result?
You could get a flat array of values of the objects.
let array = [{ 1: { date: "2014-04-23 00:00:00", volumetrie: "22458" } }, { 2: { date: "2014-05-02 00:00:00", volumetrie: "30585" } }, { 3: { date: "2014-03-27 00:00:00", volumetrie: "49536" } }], result = array.flatMap(Object.values); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Assuming the objects in your array always have one enumerable property, you can do it with map
and Object.values
:
array = array.map(obj => Object.values(obj)[0]);
Live Example:
let array = [ {1: { "date": "2014-04-23 00:00:00", "volumetrie": "22458" }}, {2: { "date": "2014-05-02 00:00:00", "volumetrie": "30585" }}, {3: { "date": "2014-03-27 00:00:00", "volumetrie": "49536" }} ]; array = array.map(obj => Object.values(obj)[0]); console.log(array);
.as-console-wrapper { max-height: 100% !important; }
But see also Nina's solution using flatMap
, which is just beautiful.
You can simply map every item in the array to a new item, which is the value of the first key of the original item:
let array = [ { 1: { "date": "2014-04-23 00:00:00", "volumetrie": "22458" }}, { 2: { "date": "2014-05-02 00:00:00", "volumetrie": "30585" }}, { 3: { "date": "2014-03-27 00:00:00", "volumetrie": "49536" }} ]; let formatted = array.map(v => { for (let k in v) return v[k]; }); console.log(formatted);
Try this:
const oldData = [
{1: {
"date": "2014-04-23 00:00:00",
"volumetrie": "22458"
}},
{2: {
"date": "2014-05-02 00:00:00",
"volumetrie": "30585"
}},
{3: {
"date": "2014-03-27 00:00:00",
"volumetrie": "49536"
}}
];
const newData = [];
for (let i = 0; i < oldData.length; i++) {
newData[i] = oldData[i][i+1];
}
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.