Javascript 下划线JS-按属性分组对象并打印它们
我有这个阵列:Javascript 下划线JS-按属性分组对象并打印它们,javascript,arrays,underscore.js,Javascript,Arrays,Underscore.js,我有这个阵列: var ty = [ { "Language": "en-GB", "Section": "Sales", "ItemName": "Type", "Texts": "Having selected the account heading select the calculation ..." }, { "Language": "en-GB", "Section": "Sales",
var ty = [
{
"Language": "en-GB",
"Section": "Sales",
"ItemName": "Type",
"Texts": "Having selected the account heading select the calculation ..."
},
{
"Language": "en-GB",
"Section": "Sales",
"ItemName": "Try",
"Texts": "This is not happenning tho ..."
},
{
"Language": "en-GB",
"Section": "Taxes",
"ItemName": "Save",
"Texts": "The Master Tax Table has been pre populated with the current UK, ..."
}];
我需要对它进行分组,根据节,它将包含具有相同节的所有属性,如下所示:
[
{section: 'Sales', ItemName: ['Type', 'Try'] Texts: ["Having selected the account heading select the calculation ...", "This is not happenning tho."]},
{section: 'Taxes', ItemName: ['Type'] Texts: ['Having selected the account heading select the calculation.']}
]
所以当我打印它时,它将只打印每个部分的文本
这是我目前掌握的代码:
var log = function(contents) {
if (_.isArray(contents)) {
_.each(contents, function(e, i, l) {
log(e);
$('#result');
$('#result').append('</br></br>');
});
} else {
console.log(contents);
$('#result').append(contents);
}
};
var ty = [
{
"Language": "en-GB",
"Section": "Sales",
"ItemName": "Type",
"Texts": "Having selected the account heading select the calculation ..."
},
{
"Language": "en-GB",
"Section": "Sales",
"ItemName": "Try",
"Texts": "This is not happenning tho ..."
},
{
"Language": "en-GB",
"Section": "Taxes",
"ItemName": "Save",
"Texts": "The Master Tax Table has been pre populated with the current UK, ..."
}];
var out = [];
_.groupBy(ty.Section, function(item){
section: item.Section
_.each(ty, function(item) {
var hold = {};
hold.options = {};
hold.options.section[item.ItemName] = {
text: item.Texts,
};
out.push(hold)
});
});
log(out);
但它仍然不会打印任何东西。在我的开发工具中,它没有显示任何内容
有什么提示吗?您可以不加下划线地完成:
var ty=[{语言:“en GB”,部分:“销售”,项目名称:“类型”,文本:“选择账户标题后选择计算…”,{语言:“en GB”,部分:“销售”,项目名称:“尝试”,文本:“这不是发生的…”,{语言:“en GB”,部分:“税收”,项目名称:“保存”,文本:“主税表已预先填入当前英国,…”}];
var节={};
ty.forEach(o=>sections[o.Section]=(sections[o.Section]| | |[])。concat(o));
var result=Object.keys(sections.map)(k=>({
第k节,
ItemName:sections[k].map(s=>s.ItemName),
文本:节[k].map(s=>s.text),
}));
console.log(result);
@GeorgeXReplay。我添加了一个下划线版本的javascript代码。
//More code above
_.each(ty, function(item) {
iName: item.itemName;
var hold = {};
hold.options = {};
hold.options.section.iName = {
text: item.Texts,
};
out.push(hold)