2 回答

TA貢獻(xiàn)1775條經(jīng)驗(yàn) 獲得超8個贊
您的目標(biāo)數(shù)據(jù)模型似乎有點(diǎn)不理想,因?yàn)槟幸粋€具有唯一 id 的數(shù)組,作為以 id 作為鍵的對象,它的性能可能更高,但您也可以使用數(shù)據(jù)模型:
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;
}, []))

TA貢獻(xiàn)1111條經(jīng)驗(yàn) 獲得超0個贊
您可以解構(gòu)屬性并稍后使用哈希表中的值。
主要部分是獲取具有l(wèi)anguage屬性的初始對象。
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"] }],
result = data.reduce((c, { id, lang, title, bodyText, keywords }) => {
c[id] = c[id] || { id, language: {} };
c[id].language[lang] = { title, bodyText, keywords };
return c;
}, {}),
array = Object.values(result);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
添加回答
舉報