我想重新排列一个物体的结构,我从昨天开始就卡住了,所以我需要你的重要帮助。
目前,结构如下:
var data = [{
id: 14,
language: "english",
title: "I am a new article",
bodyText: "Article Content",
lang: "eng",
keywords: ["key1", "key2"]
},
{
id: 1,
language: "greeks",
title: "Ειμαι ενα καινουρειο αρθρο",
bodyText: "Κυριο μερος Αρθρου",
lang: "gr",
keywords: ["key1", "key2"]
},
{
id: 1,
language: "espanol",
title: "Soy un nuevo articulo",
bodyText: "Soy un nuevo articulo",
lang: "es",
keywords: ["key1", "key2"]
},
]
我想将结构重新排列为以下格式:
var data = [{
id: 1,
language: {
es: {
title: "Spanish Article",
bodyText: "Content in Spanish"
},
gr: {
title: "Greek Article",
bodyText: "Content in Grecce"
}
},
id: 2,
language: {
en: {
title: "English Article",
bodyText: "Content in English"
}
}
}];
我编写了以下代码来完成任务,但没有运气。
var arr = [];
let result = data.reduce(function(c, v) {
console.log(v.id);
/* console.log(c);
*/
c[v.id] = c[v.id] || {};
c[v.id][v.lang] = c[v.id][v.lang] || {
title: v.title,
bodyText: v.bodyText,
keywords: v.keywords
};
arr.push(c)
return c;
}, {});
console.log(arr);
我得到一个如下所示的对象:
[{
id:1,
es:{
title:"Spanish Article",
bodyText:"Content in Spanish"
},
gr:{
title:"Greek Article",
bodyText:"Content in Grecce"
},
id:2,
en:{
title:"English Article",
bodyText:"Content in English"
}
}]
欢迎任何推荐,提前感谢社区!
www说
catspeake
相关分类