javascript - 重新排列 javascript 对象结构
问题描述
我想重新安排一个对象的结构,从昨天开始就卡住了,所以我需要你的重要帮助。
目前,结构如下:
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"
}
}]
欢迎任何建议,提前感谢社区!
解决方案
您的目标数据模型似乎有点不理想,因为您有一个具有唯一 id 的数组,它可以作为一个以 id 作为键的对象更高效,但您也可以摆脱您的数据模型:
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"]
}
];
console.log(data.reduce(function(result, entry) {
var id_index = result.map(function(e) { return e.id; }).indexOf(entry.id);
var id_element;
if (id_index === -1) {
id_element = {id: entry.id, language: {}};
} else {
id_element = result[id_index];
}
id_element.language[entry.lang] = {
title: entry.title,
bodyText: entry.bodyText
};
if (id_index === -1) {
result.push(id_element);
}
return result;
}, []))
推荐阅读
- multithreading - 为什么 View 中的请求会导致树侦听器在非 gui 模式下显示“没有要显示的数据”
- amazon-redshift - 创建具有对给定架构(包括删除表)的访问权限的 aws redshift 用户
- jquery - 如何获取元素的父母、祖父母和曾祖父母?
- unity3d - 画布缩放器问题
- sitecore - Sitecore Commerce 商务工具无法加载
- google-analytics - 如何将 Google Analytics 数据导出到 Google GCS 存储桶或 BigQuery?
- big-o - 如何证明以下哪个函数的增长率更大
- excel - 如何从文件路径中提取文件夹
- r - 提取非负数或从字符串向量中返回负数
- c# - 当字段中的字符数减少时,更改 DataGridTextColumn 的宽度