Home > Blockchain >  Push object into same key in Javascript
Push object into same key in Javascript

Time:07-11

I have an array like below format :

let data = [
    {
       date: "2022-07-22T08:55:07.438",
        title: "Test topic meeting "
    },
    {
       date: "2022-07-22T08:55:07.438",
        title: "virtual log"
    },
    {
       date: "2022-07-23T08:55:07.438",
        title: "Hello test"
    },
]

Now, I need an object like in the below format,

{
    "2022-07-22": [
        {
           date: "2022-07-22T08:55:07.438",
            title: "Test topic meeting"
        },
        {
           date: "2022-07-22T08:55:07.438",
            title: "Test topic meeting"
        }
    ],
    "2022-07-23": [
        {
           date: "2022-07-23T08:55:07.438",
            title: "Hello test"
        }
    ]
}

I need to filter data in date format and pushing the same value and key in the same date.

Thanks in advance!!!

CodePudding user response:

Simply using for-loop with grouping by date:

let data = [
    {
       date: "2022-07-22T08:55:07.438",
        title: "Test topic meeting "
    },
    {
       date: "2022-07-22T08:55:07.438",
        title: "virtual log"
    },
    {
       date: "2022-07-23T08:55:07.438",
        title: "Hello test"
    },
]
const output = {};
for (let obj of data) {
    let date = obj.date.split('T')[0];
    if(output[date] == undefined){
        output[date] = [obj]
    }else{
        output[date].push(obj)
    }
}
console.log(output)

CodePudding user response:

const sameYears = [...new Set(data.map(x => x.date.slice(0, 10)))];
const newData = sameYears.reduce((acc, x) => ({...acc, [x]: data.filter(el => el.date.includes(x))}), {});

CodePudding user response:

You can iterate through the elements in the array data and then, split the dates from T after that check if the answer object already has the date as a key, then push the element to the answer[date] array. And if the answer doesn't have date then add element to the answer[date].

Example:

let data = [
    {
       date: "2022-07-22T08:55:07.438",
        title: "Test topic meeting "
    },
    {
       date: "2022-07-22T08:55:07.438",
        title: "virtual log"
    },
    {
       date: "2022-07-23T08:55:07.438",
        title: "Hello test"
    },
]
const answer = {};
data.forEach(element=>{
    let date = element.date.split('T')[0];
    if(answer[date] != undefined){
        answer[date].push(element)
    }else{
        answer[date] = [element]
    }
})
console.log("data::>",data)
console.log("answer::>",answer)

  • Related