i wanna ask my case about array and object, i still less of knowledge about this because still newbie. i have bunch of data as following:
counterTraffic : [
{
id: 1,
daerah: "Bandung",
date:"1668790800000",
kendaraan: [
{rodaEmpat: 50},
{rodaDua: 22},
{truck: 30},
{Bus: 70},
]
}, {
id: 2,
daerah: "Tasik",
date:"1668877200000",
kendaraan: [
{rodaEmpat: 80},
{rodaDua: 15},
{truck: 10},
{Bus: 50},
]
},
{
id: 3,
daerah: "Bekasi",
date:"1669050000000",
kendaraan: [
{rodaEmpat: 30},
{rodaDua: 65},
{truck: 20},
{Bus: 100},
]
}
,
{
id: 4,
daerah: "Bandung",
date:"1668963600000",
kendaraan: [
{rodaEmpat: 20},
{rodaDua: 15},
{truck: 5},
{Bus: 150},
]
}
]
and i want take value data of counterTraffic.kendaraan and assign to new variable. so when i go mapping the counterTraffic, and then assign to new variable with kendaraan data
the result have to become: let kendaraanNew = [50,22,30,70]
the data above from counterTraffic[0].kendaraan that already mapping before.
thank you for your helping
CodePudding user response:
You can define a funciton like below:
function getKendaraan(index) {
return counterTraffic[index].kendaraan
.map(item => Object.values(item)[0])
.reduce((acc, cur) => [...acc, cur], [])
}
And use like this: let kendaraanNew = getKendaraan(0)
Can this resolve your problem?
CodePudding user response:
Is this what was expected
const mappedCounterTraffic = counterTraffic.map((item) => {
const kendaraanNew = Object.entries(item.kendaraan).reduce((acc, cur) => {
const item = cur[1];
const newItems = Object.entries(item).reduce((ac, cu) => {
return [...ac, cu[1]];
}, []);
return [...acc, ...newItems];
}, []);
console.log("--------", kendaraanNew);
return {
...item,
kendaraanNew
};
});
console.log(mappedCounterTraffic);
}
Response
[
{
"id":1,
"daerah":"Bandung",
"date":"1668790800000",
"kendaraan":[
{
"rodaEmpat":50
},
{
"rodaDua":22
},
{
"truck":30
},
{
"Bus":70
}
],
"kendaraanNew":[
50,
22,
30,
70
]
},
{
"id":2,
"daerah":"Tasik",
"date":"1668877200000",
"kendaraan":[
{
"rodaEmpat":80
},
{
"rodaDua":15
},
{
"truck":10
},
{
"Bus":50
}
],
"kendaraanNew":[
80,
15,
10,
50
]
},
{
"id":3,
"daerah":"Bekasi",
"date":"1669050000000",
"kendaraan":[
{
"rodaEmpat":30
},
{
"rodaDua":65
},
{
"truck":20
},
{
"Bus":100
}
],
"kendaraanNew":[
30,
65,
20,
100
]
},
{
"id":4,
"daerah":"Bandung",
"date":"1668963600000",
"kendaraan":[
{
"rodaEmpat":20
},
{
"rodaDua":15
},
{
"truck":5
},
{
"Bus":150
}
],
"kendaraanNew":[
20,
15,
5,
150
]
}
]