Javascript 对象内具有相同类型的临时换行数组项
这是从json api接收的内容的一部分Javascript 对象内具有相同类型的临时换行数组项,javascript,arrays,json,algorithm,object,Javascript,Arrays,Json,Algorithm,Object,这是从json api接收的内容的一部分 contents: [ { title: "some title", content_type: 2 }, { title: "some title", content_type: 2 }, { title: "some title", content_type: 1 }, { title: "some title", content_type: 2 }, { title: "some title", content_type: 1 }, ]
contents: [
{ title: "some title", content_type: 2 },
{ title: "some title", content_type: 2 },
{ title: "some title", content_type: 1 },
{ title: "some title", content_type: 2 },
{ title: "some title", content_type: 1 },
]
对于我来说,要对这些数据执行操作,可以更轻松地将具有相同类型的项包装到一个单独的数组中,例如:
contents: [
type2: [
{ title: "some title", content_type: 2 },
{ title: "some title", content_type: 2 }
],
{ title: "some title", content_type: 1 },
{ title: "some title", content_type: 2 },
{ title: "some title", content_type: 1 },
]
注意,还有另一个类型为2的内容,但由于它是单个内容,因此无需将其包装在临时数组中。我需要找到一种有效的方法,并且在需要发布到服务器时能够快速删除此包装
var contents= [
{ title: "some title", content_type: 2 },
{ title: "some title", content_type: 2 },
{ title: "some title", content_type: 1 },
{ title: "some title", content_type: 2 },
{ title: "some title", content_type: 1 },
];
var wrap = function(contents) {
var obj = {};
contents.forEach(function(row) {
var key = 'type' + row.content_type;
if (!obj[key]) {
obj[key] = [];
}
obj[key].push(row);
});
return obj;
};
var contents2 = wrap(contents);
console.log(contents2);
var unwrap = function(contents) {
var arr = [];
for (var i in contents) {
arr = arr.concat(contents[i]);
}
return arr;
};
var contents3 = unwrap(contents2);
console.log(contents3);
这给了你:
{ type2:
[ { title: 'some title', content_type: 2 },
{ title: 'some title', content_type: 2 },
{ title: 'some title', content_type: 2 } ],
type1:
[ { title: 'some title', content_type: 1 },
{ title: 'some title', content_type: 1 } ] }
[ { title: 'some title', content_type: 2 },
{ title: 'some title', content_type: 2 },
{ title: 'some title', content_type: 2 },
{ title: 'some title', content_type: 1 },
{ title: 'some title', content_type: 1 } ]
结果看起来无效。内容要么是对象,类型1错误;要么是数组,类型1错误。type1的内部是一个数组…?@NinaScholz我的错误,更正了您需要在数组中的一个单独属性中使用type2吗?@NinaScholz type2只是一个名称,指的是它嵌套的项目上的内容类型,它可以被命名为任何名称。我认为您需要提供更多关于您需要完成什么以及为什么这样做的详细信息。正如Nina指出的,您想要的结果甚至不是JavaScript中的有效数据结构。您希望执行哪些需要更改结构的处理?这里的问题是,我希望包装前2项,保留1项未包装,保留2项未包装等。。因此,在一个nut shel中,只有在数组中紧跟其后的相同类型才需要被包装