Home > Enterprise >  filter javascript object with key value
filter javascript object with key value

Time:08-30

I am filtering a javascript object..

[{
   title: 'example1',
   categorySlug: 'cat-1',
   categoryName: 'hello1'
}
{
   title: 'example2',
   categorySlug: 'cat-2',
   categoryName: 'hello2'
}]

I need the object as below

[{
    categorySlug: "cat1",
    categoryName: "hello1",
    data: [{
        {
            title: "example1",
            categorySlug: 'cat-1',
            categoryName: 'hello1'
        }
    }]
},
 {
    categorySlug: "cat2",
    categoryName: "hello2",
    data: [{
        {
            title: "example2",
            categorySlug: 'cat-2',
            categoryName: 'hello2'
        }
    }]
}
]   

I need to filter the object. I have tried with many way but I have faield to filter the object.

CodePudding user response:

You can use the array map method.


array.map((category) => ({categorySlug: category.categorySlug,
   categoryName: category.categoryName, data: [category]}))

CodePudding user response:

var objectArray = [{
   title: 'example1',
   categorySlug: 'cat-1',
   categoryName: 'hello1'
},
{
   title: 'example2',
   categorySlug: 'cat-2',
   categoryName: 'hello2'
}]

var newArray = [];

for (let i = 0; i < objectArray.length; i  ) {
   const items = objectArray[i];
    newArray.push({
      categorySlug: items.categorySlug,
      categoryName: items.categoryName,
       data: [items]
    })

}

console.log(newArray)

  • Related