首页 > 解决方案 > 重新排列 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"
}
}]

欢迎任何建议,提前感谢社区!

标签: javascriptobjectjavascript-objects

解决方案


您的目标数据模型似乎有点不理想,因为您有一个具有唯一 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;
}, []))


推荐阅读