如何迭代对象数组广告返回匹配的对象 [英] How to iterate over array of objects ad return matched object
问题描述
我有一个从A到Z的字母数组,以及对象数组(具有属性和值),我必须根据字母表遍历品牌对象和组,例如,如果字母是我们必须将所有brand_name分组以字母A开头,即Adidas和adidas_orignals ,我使用 .map和.filter
获取相应的功能,任何人都可以帮助我提供上述功能,在此先感谢
I have an array of alphabets from A to Z, and array of objects(which has properties and values), I have to traverse the brand object and group according to the alphabet, for example, if the alphabet is A than we have to group all brand_name start with letter A i.e Adidas and adidas_orignals, I am using.map and .filter
for the appropriate functionality, Can anyone help me out for the above functionality, thanks in advance
const en_alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
const brands = [
{id:1, brand_name: 'adidas', brand_trans: 'أديداس', isPremium: true, url: '/brands/adidas'},
{id:2, brand_name: 'adidas Originals', brand_trans: 'أديداس اوريجينال', isPremium: false, url: '/brands/adidas-originals'},
{id:4, brand_name: 'Bodyism', brand_trans: 'بودييزم', isPremium: false, url: '/brands/bodyism'},
{id:5, brand_name: 'Columbia', brand_trans: 'كولومبيا', isPremium: false, url: '/brands/columbia'},
{id:5, brand_name: 'Converse', brand_trans: 'كونفرس', isPremium: true, url: '/brands/converse'},
];
返回值应与下面相同
return value should be same as below
{
brand_group_title: 'a',
brand_list: [
{id:1, brand_name: 'adidas', brand_trans: 'أديداس', isPremium: true, url: '/brands/adidas'},
{id:2, brand_name: 'adidas Originals', brand_trans: 'أديداس اوريجينال', isPremium: false, url: '/brands/adidas-originals'},
]
}
{
brand_group_title: 'b',
brand_list: [
{id:4, brand_name: 'Bodyism', brand_trans: 'بودييزم', isPremium: false, url: '/brands/bodyism'},
]
}
{
brand_group_title: 'c',
brand_list: [
{id:5, brand_name: 'Columbia', brand_trans: 'كولومبيا', isPremium: false, url: '/brands/columbia'},
{id:5, brand_name: 'Converse', brand_trans: 'كونفرس', isPremium: true, url: '/brands/converse'},
]
}
我尝试了什么:
我正在使用.map和.filter函数用于上面的
What I have tried:
I am using .map and .filter function for the above
let printData = [];
var printList = brands.filter(function(str) {
return str.map(function(char) {
this.brand_name.charAt(0) === str;
});
});
推荐答案
试试
try
var result = [];
for (var i = 0; i<en_alpha.length; i ++){
var ch = en_alpha[i];
var matchedItems = brands.filter(function (obj){ return obj.brand_name.toLowerCase().startsWith(ch)})
if(matchedItems.length>0)
result.push( { brand_group_title:ch,brand_list: matchedItems } );
}
alert(JSON.stringify(result))
这篇关于如何迭代对象数组广告返回匹配的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!