gpt4 book ai didi

javascript - 在对象内临时包装具有相同类型的数组项

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:06:28 24 4
gpt4 key购买 nike

这是从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: [
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 } ]

关于javascript - 在对象内临时包装具有相同类型的数组项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35296080/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com