gpt4 book ai didi

javascript - 如何对每 x 项的 JSON 项进行分组

转载 作者:行者123 更新时间:2023-11-30 15:25:35 26 4
gpt4 key购买 nike

我有一些动态生成的 JSON 数据,需要按特定数字进行分组。所以我有办法为数字生成变量,但需要根据该数字对项目进行分组。这是原始的 JSON:

"items":[
{"name":"School","value":"sdf"},
{"name":"Year","value":"dsf"},
{"name":"GPA","value":"Sdfdsf"},
{"name":"School","value":"sdf"},
{"name":"Year","value":"dsf"},
{"name":"GPA","value":"Sdfdsf"},
]

我需要它按每 3 个项目分组,格式如下:

"items":[
"item":{
"School":"sdf",
"Year":"dsf",
"GPA":"Sdfdsf"
},
"item":{
"School":"sdf",
"Year":"dsf",
"GPA":"Sdfdsf"
}
]

这是我当前的代码:

    var newData = "items": [];

jQuery('.dynamicRow input').each(function() {
var dName = jQuery(this).closest('input').attr('name');
var dValue = jQuery(this).closest('input').val();
var obj = {
name: dName,
value: dValue
};

newData.items.push(obj);
});

jQuery('#debug').text(JSON.stringify(newData));

最佳答案

你可以使用 Array#reduce如果 i % 3 为零,则插入一个新对象。

在项目的最后一个元素添加属性。

var data = { "items": [{ "name": "School", "value": "sdf" }, { "name": "Year", "value": "dsf" }, { "name": "GPA", "value": "Sdfdsf" }, { "name": "School", "value": "sdf" }, { "name": "Year", "value": "dsf" }, { "name": "GPA", "value": "Sdfdsf" }] },
result = {
items: data.items.reduce(function (r, a, i) {
if (!(i % 3)) {
r.push({});
}
r[r.length - 1][a.name] = a.value;
return r;
}, [])
};

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如何对每 x 项的 JSON 项进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43034699/

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