我正在尝试转换看起来像这样的对象数组:
var allApps = [
{
title: "amazon",
summary: "lorem ipsum"
},
{
title: "facebook",
summary: "lorem ipsum"
},
{
title: "twitter",
summary: "lorem ipsum"
},
{
title: "flipp",
summary: "lorem ipsum"
}
]
变成这样的东西:
var titles= {
A: [
{
title: "amazon",
summary: "lorem ipsum"
}
],
F: [
{
title: "facebook",
summary: "lorem ipsum"
},
{
title: "flipp",
summary: "lorem ipsum"
}
],
T: [
{
title: "twitter",
summary: "lorem ipsum"
}
]
}
到目前为止,我有这个:
var letters = [];
var titles = [];
for (var i = 0; i < allApps.length; i++) {
title = allApps[i].title;
if (title=="") {
continue;
}
var firstLetter = title.substring(0,1);
var arrayWithFirstLetter = titles[firstLetter];
if (arrayWithFirstLetter == null) {
titles[firstLetter] = [];
letters.push(firstLetter);
};
}
我本质上是想根据title属性对应用程序进行排序,然后将它们与相应字母一起推入数组。
现在,我的代码获取每个标题的第一个字母,并为每个字母创建一个数组数组
答案 0 :(得分:1)
怎么样:
var allApps = [
{
title: "amazon",
summary: "lorem ipsum"
},
{
title: "facebook",
summary: "lorem ipsum"
},
{
title: "twitter",
summary: "lorem ipsum"
},
{
title: "flipp",
summary: "lorem ipsum"
}
]
var d = {};
for (var i=0; i<allApps.length; i++) {
var l = allApps[i].title.substring(0,1);
// ensure object has key
if (!d[l]) d[l] = [];
d[l].push(allApps[i]);
}
console.log(d)
此日志:
{
a: [
{ title: 'amazon', summary: 'lorem ipsum' }
],
f:[
{ title: 'facebook', summary: 'lorem ipsum' },
{ title: 'flipp', summary: 'lorem ipsum' }
],
t: [
{ title: 'twitter', summary: 'lorem ipsum' }
]
}
这里的想法是,我们只需遍历allApps
,检查该数组当前成员上title属性的第一个字母,然后检查该字母是否已成为我们新字典{{1 }}。如果不是,我们在d
中将该字母添加为键。然后,将d
中的当前元素添加到该键的值列表中。就是这样!
答案 1 :(得分:1)
使用reduce函数,并从当前对象获得第一个字符。第一个角色将是。如果该密钥存在,则更新其值
var allApps = [{
title: "amazon",
summary: "lorem ipsum"
},
{
title: "facebook",
summary: "lorem ipsum"
},
{
title: "twitter",
summary: "lorem ipsum"
},
{
title: "flipp",
summary: "lorem ipsum"
}
]
let k = allApps.reduce(function(acc, curr) {
let getFirstChar = curr.title.charAt(0).toUpperCase();
if (acc[getFirstChar] === undefined) {
acc[getFirstChar] = [];
}
acc[getFirstChar].push(curr)
return acc;
}, {})
console.log(k)
答案 2 :(得分:0)
您不需要变量letters
。您应该使用titles[firstletter]
。
titles
应该初始化为对象,而不是数组。
var allApps = [
{
title: "amazon",
summary: "lorem ipsum"
},
{
title: "facebook",
summary: "lorem ipsum"
},
{
title: "twitter",
summary: "lorem ipsum"
},
{
title: "flipp",
summary: "lorem ipsum"
}
];
var titles = {};
for (var i = 0; i < allApps.length; i++) {
title = allApps[i].title;
if (title == "") {
continue;
}
var firstLetter = title.substring(0, 1).toUpperCase();
if (!titles[firstLetter]) {
titles[firstLetter] = [];
};
titles[firstLetter].push(allApps[i]);
}
console.log(titles);