[英]filter javascript object with key value
我正在过滤 javascript object..
[{
title: 'example1',
categorySlug: 'cat-1',
categoryName: 'hello1'
}
{
title: 'example2',
categorySlug: 'cat-2',
categoryName: 'hello2'
}
{
title: 'example3',
categorySlug: 'cat-1',
categoryName: 'hello1'
}]
我需要 object 如下
[{
categorySlug: "cat1",
categoryName: "hello1",
data: [{
{
title: "example1",
categorySlug: 'cat-1',
categoryName: 'hello1'
},
{
title: "example1",
categorySlug: 'cat-1',
categoryName: 'hello1'
}
}]
},
{
categorySlug: "cat2",
categoryName: "hello2",
data: [{
{
title: "example2",
categorySlug: 'cat-2',
categoryName: 'hello2'
}
}]
}
]
我需要过滤 object。 我尝试了很多方法,但未能过滤 object。
#我已经添加了一个类别并且我需要像这样过滤。
您可以使用数组 map 方法。
const array = [{
title: 'example1',
categorySlug: 'cat-1',
categoryName: 'hello1'
}
{
title: 'example2',
categorySlug: 'cat-2',
categoryName: 'hello2'
}]
// map over the objects within array
const newArray = array.map((category) => ({ categorySlug: category.categorySlug,
categoryName: category.categoryName, data: [category] }))
请记住 map 方法不会改变原始数组。 意思是 'array' 将保持不变,但 'newArray' 将包含您的新数组和您的新数据结构
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)
您想要实现的更像是分组而不是过滤。 我认为下面的脚本会让你满意。
const array = [{ title: 'example1', categorySlug: 'cat-1', categoryName: 'hello1' }, { title: 'example2', categorySlug: 'cat-2', categoryName: 'hello2' }, { title: 'example3', categorySlug: 'cat-1', categoryName: 'hello1' }] const result = array.filter((value, index, self) => index === self.findIndex((item) => item.categoryName === value.categoryName)).map(({ title, ...category }) => { return {...category, data: array.filter((item) => item.categoryName === category.categoryName) }; }); console.log(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.