I want to modify JSON data in React js I have a sample JSON file
[
{
"id": 1,
"name": "A",
"day": "mon",
"candidate": 5
},
{
"id": 2,
"name": "A",
"day": "mon",
"candidate": 4
},
{
"id": 3,
"name": "A",
"day": "mon",
"candidate": 3
},
{
"id": 4,
"name": "A",
"day": "tue",
"candidate": 2
}
]
I want to change like this format bellow
const data = {
Monday: [
{day: "mon", name: 'A', candidate: '5'},
{day: "mon", name: 'A', candidate: '4'},
{day: "mon", name: 'A', candidate: '3'}
],
tuesday: [
{day: "tue", name: 'B', candidate: '1'},
]
}
Please help me to change to this format :(
Edit I try to make JSON data to what data I want, but the final result temp is only tue not mon ?
useEffect(() => {
let temp = {};
dataJson.forEach(item => {
if(item.day === 'mon'){
const newArr = {moday: item}
temp = newArr;
}
if(item.day === 'tue'){
const newArr = {tue: item}
temp = newArr;
}
});
console.log("tempt", temp)
}, [])
CodePudding user response:
Example : you can put in a loop if you want
const data =
[
{
"id": 1,
"name": "A",
"day": "mon",
"candidate": 5
},
{
"id": 2,
"name": "A",
"day": "mon",
"candidate": 4
},
{
"id": 3,
"name": "A",
"day": "mon",
"candidate": 3
},
{
"id": 4,
"name": "A",
"day": "tue",
"candidate": 2
}
]
console.log(data.filter(item => item.day === 'mon'))
CodePudding user response:
it can help you
const data = [
{
"id": 1,
"name": "A",
"day": "mon",
"candidate": 5
},
{
"id": 2,
"name": "A",
"day": "mon",
"candidate": 4
},
{
"id": 3,
"name": "A",
"day": "mon",
"candidate": 3
},
{
"id": 4,
"name": "A",
"day": "tue",
"candidate": 2
}
]
let newNewData = []
data.map(item => {
return newNewData.push({[item.day]: item})
})
console.log(newNewData)